【问题标题】:Microsoft Graph API Mail.Send Access DeniedMicrosoft Graph API Mail.Send 访问被拒绝
【发布时间】:2020-10-13 15:09:20
【问题描述】:

我已在 Azure Active Directory 中注册了一个应用程序作为使用客户端机密进行身份验证的守护程序。我添加了 Graph API 权限并已授予管理员许可以获取共享点列表,并且可以在 c# 中使用 Graph API 成功拉取。我还授予管理员对 Mail.Send Graph API 的同意,但访问被拒绝。呼叫设置正确,我用作“发件人”字段的电子邮件地址是管理员邮箱。我正在做一些额外的配置或遗漏配置吗?

调用验证

var clientSecret = @"{My generated Secret in Azure}";
var clientId = @"{My Client Id}";
var tenantID = @"{My Tenant Id}";
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantID)
.WithClientSecret(clientSecret)
.Build();
ClientCredentialProvider authenticationProvider = new ClientCredentialProvider(confidentialClientApplication);
return new GraphServiceClient(authenticationProvider);

我的呼叫代码发送电子邮件

System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.StreamWriter writer = new System.IO.StreamWriter(ms);
writer.Write(htmlDocument.Text);
writer.Flush();
writer.Dispose();
MessageAttachmentsCollectionPage attachments = new MessageAttachmentsCollectionPage();
attachments.Add(new FileAttachment
{
ODataType = "#microsoft.graph.fileAttachment",
ContentBytes = ms.ToArray(),
ContentType = "text/html",
ContentId = "testing",
Name = "My_Report.html"
});
var message = new Message
{
Subject = "My Report",
Body = new ItemBody
{
ContentType = BodyType.Text,
Content = "Here is your updated report from list"
},
ToRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "{End User to receive report}"
}
}
},
CcRecipients = new List<Recipient>()
{
new Recipient
{
EmailAddress = new EmailAddress
{
Address = "{my admin email account}"
}
}
},
From = new Recipient { 
EmailAddress = new EmailAddress
{ 
Address = "{my admin email account}"
}
},
Attachments = attachments
};
var graphServiceClient = GetGraphServiceClient();
await graphServiceClient.Me
.SendMail(message, null)
.Request()
.PostAsync();

【问题讨论】:

  • 当 API 调用由于配置的应用程序访问策略而被拒绝访问时,您可能会遇到错误“ErrorAccessDenied”。如果来自您的应用的 Microsoft Graph API 调用返回此错误,请与您的组织的 Exchange Online 管理员合作,以确保您的应用有权访问邮箱资源。请参阅相关文档 - docs.microsoft.com/en-us/graph/auth-limit-mailbox-access
  • 您好,我的回答对您有帮助吗?如果我的回答对您有帮助,您可以接受它作为回答。这对其他社区成员可能会有所帮助。谢谢。:)

标签: c# azure-active-directory microsoft-graph-api office365 microsoft-graph-mail


【解决方案1】:

您正在使用客户端凭据流。

当作为应用程序进行身份验证时(而不是使用用户),您不能使用委派权限 - 由用户授予的范围。您必须使用应用程序权限,也称为角色,由管理员为应用程序授予或通过 Web API 的预授权授予。

因此,您应该在门户中授予应用应用程序权限并授予管理员许可。

并修改如下代码。

  await graphClient.Users["your admin email account"]
                .SendMail(message, null)
                .Request()
                .PostAsync();

【讨论】:

  • 按照建议更改代码有效。我确实有正确的身份验证设置。非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多