gpt4 book ai didi

c# - Office 365 客户端 API SendMailAsync 返回未授权

转载 作者:行者123 更新时间:2023-11-30 20:39:25 25 4
gpt4 key购买 nike

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

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


未经授权

描述:当前网络请求执行过程中出现未处理的异常。请查看堆栈跟踪以获取有关错误及其在代码中的来源的更多信息。

异常详细信息: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显示该 token 未包含在 SendMailAsync 创建的请求中,但是我可以看到该 token 包含在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com