Microsoft Graph API Mail.Send 拒绝访问

Microsoft Graph API Mail.Send Access Denied

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

调用验证 </p> <pre><code>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);

我发送电子邮件的调用代码 </p> <pre><code>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();

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

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

所以您应该在门户中授予应用程序应用程序权限并授予管理员同意。

并修改以下代码。

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