发送电子邮件 OAuth2 Office365

问题描述 投票:0回答:1

我通过在 Microsoft Azure 服务中注册应用程序获得了应用程序的 clientId、tenantId 和密钥。

我设法从这里获得了一个令牌:https://login.microsoftonline.com/{tenantId} 我还发现范围应该是这样的:https://graph.microsoft.com/.default

我尝试用 https://graph.microsoft.com/v1.0/me/sendMail endPoint 发送电子邮件,但我终于意识到他/我对我不好(我尝试替换“我”)与我想要发送电子邮件的电子邮件地址,但这也不起作用)。

请帮我如何使用这个API?我只想用 OAuth2 发送电子邮件,这就是我想要的。我什至愿意用 PostRequests 手动完成。我不在乎了,只要告诉我如何使用这个“可爱的”微软服务..

c# azure oauth-2.0 microsoft-graph-api office365api
1个回答
0
投票

我注册了一个 Azure AD 应用程序并授予了

Mail.Send
Application 类型的权限,如下所示:

enter image description here

现在,我通过 Postman 使用客户端凭据流生成了 访问令牌,参数如下:

POST https://login.microsoftonline.com/tenantId/oauth2/v2.0/token
grant_type:client_credentials
client_id: appId
client_secret: secret 
scope: https://graph.microsoft.com/.default

回复:

enter image description here

您可以在 jwt.ms 中解码上述令牌,并检查它是否具有 Mail.Send

 权限的 
roles 声明:

enter image description here

当我使用此令牌通过 Postman 通过以下 API 调用发送邮件时,我得到了响应,如下所示:

 POST https://graph.microsoft.com/v1.0/users/userId/sendMail
 {
  "message": {
    "subject": "Invitation for Diwali Event",
    "body": {
      "contentType": "Text",
      "content": "Hi Sri! We welcome you to attend Diwali event on 2 November 2023"
    },
    "toRecipients": [
      {
        "emailAddress": {
          "address": "[email protected]"
        }
      }
    ]
  },
  "saveToSentItems": "true"
}

回复:

enter image description here

为了确认,我在用户的

Sent Items
中检查了邮件成功发送的位置,如下所示:

enter image description here

在您的情况下,“访问被拒绝。检查凭据并重试”如果您为客户端凭据流程授予

Mail.Send
委托类型的权限,则会发生错误。

解决错误,请确保授予

Mail.Send
Application类型的权限。请参阅我之前回答过的SO 主题

© www.soinside.com 2019 - 2024. All rights reserved.