我正在尝试从C#中的ASP MVC Web应用程序设置Office 365集成,为此我正在使用Outlook Mail REST API(客户端版本)。我一直在这里使用API​​参考:https://msdn.microsoft.com/office/office365/APi/mail-rest-operations

我可以正常登录Office 365,并获取令牌,然后阅读邮件文件夹(即已发送邮件/收件箱),但是当我尝试发送电子邮件时出现以下错误:



未经授权

说明:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪,以获取有关错误及其在代码中起源的更多信息。

异常详细信息:Microsoft.OData.Client.DataServiceClientException:未经授权



我已经添加了读取/写入和发送电子邮件的权限,因此,当我登录Office 365时会说:

Office Integration Test App needs permission to:

Access your data anytime
Sign in as you
Send mail as you
Read and write access to your mail


因此,我认为“按需发送邮件”是我所需要的。但是,我仍然收到Unathorized错误消息。

这是我正在运行的用于发送电子邮件的代码:

    string AccessToken = (string)Session["Office365Token"];

    OutlookServicesClient client = new OutlookServicesClient(new Uri("https://outlook.office.com/api/v2.0"),
        async () =>
        {
            return AccessToken;
        });

    ItemBody EmailBody = new ItemBody
    {
        Content = "Test email from the project",
        ContentType = BodyType.HTML
    };

    List<Recipient> toRecipients = new List<Recipient>();

    toRecipients.Add(new Recipient() { EmailAddress = new EmailAddress() { Address = "testemail@test.com" } });

    Message newMessage = new Message
    {
        Subject = "Test Subject For Email",
        Body = EmailBody,
        ToRecipients = toRecipients
    };

    await client.Me.SendMailAsync(newMessage, true);


当我调用SendMailAsync时,错误发生在最后一行。我不太确定要尝试其他什么,也找不到有关导致此问题的任何信息。

任何帮助是极大的赞赏!

最佳答案

我也一直在尝试使用OutlookServicesClient的SendMailAsync方法,并收到了未经授权的响应。

Fiddler显示该令牌未包含在SendMailAsync创建的请求中,但是我可以看到OutlookServicesClient生成读取消息的Get请求时,该令牌已包含在内。 this GitHub issue为我确认了这一点,它还说它曾经在库的1.​​0.22版中工作,但从1.0.34版开始就没有。

环顾四周后,我发现其他人尝试了alternative approach to sending mail的方法,方法是先创建草稿,然后再发送。看起来是这样的:

OutlookServicesClient outlookClient = new OutlookServicesClient(new Uri("https://outlook.office.com/api/v2.0"),
    async () =>
    {
        // already retrieved my AccessToken using AuthenticationContext
        return AccessToken;
    });

// Save to Drafts folder
await outlookClient.Me.Messages.AddMessageAsync(newMessage);

// Now send
await newMessage.SendAsync();


我的结论是,SendMailAsync方法被破坏了。通过首先将新消息保存为草稿,我们可以解决它。

关于c# - Office 365客户端API SendMailAsync返回未授权,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34359005/

10-15 15:41