跳到主内容

使用 Microsoft Graph 发送邮件

本指南介绍如何使用 Microsoft Graph 的 sendMail API 从 Microsoft 365 邮箱发送 Casdoor 的邮件。Casdoor 使用客户端凭据流从 Microsoft Entra ID 获取仅应用令牌,并调用 POST /users/<mailbox>/sendMail。它不使用 SMTP,因此适用于已关闭 SMTP AUTH 的租户。若要改为通过 SMTP 发送,请参阅 Microsoft 365。


学习目标​

  • 在 Microsoft Entra ID 中注册一个可作为邮箱发送邮件的应用。
  • 在 Casdoor 中添加 Microsoft Graph 作为邮件提供商并进行测试。

前提条件​

  • 一个 Microsoft 365 租户和一个用于发送邮件的邮箱,例如 noreply@contoso.com。共享邮箱也可以。
  • 一个可以在 Microsoft Entra ID 中注册应用并授予管理员同意的账户
  • 拥有 Casdoor 管理控制台的管理员权限

在 Microsoft Entra ID 中注册应用​

  1. 在 Microsoft Entra 管理中心 中,打开 App registrations 并点击 New registration。输入名称,例如 Casdoor email,保持 Accounts in this organizational directory only 选中状态,然后点击 Register。
  2. 在应用的 Overview 页面,复制 Application (client) ID 和 Directory (tenant) ID。
  3. 转到 Certificates & secrets > Client secrets > New client secret,并复制密钥的 Value。该值仅显示一次。
  4. 前往 API permissions > Add a permission > Microsoft Graph > Application permissions,然后选择 Mail.Send。
  5. 为你的组织点击 Grant admin consent。

Mail.Send 应用程序权限允许该应用以租户中的任何邮箱身份发送邮件。若要将其限制为仅发送邮箱,请使用 Exchange Online 中的应用 RBAC 或应用程序访问策略。

在 Casdoor 中添加提供商​

  1. 在 Casdoor 管理控制台中,前往 Identity > Providers 并添加一个提供商。

  2. 将 Category 设置为 Email,将 Type 设置为 Microsoft Graph。Casdoor 会自动填充端点、令牌 URL 和范围。

  3. 填写以下字段:

    字段值
    Client ID应用的 Application (client) ID
    Client secret客户端密钥的 Value
    From address用于发送邮件的邮箱,例如 noreply@contoso.com。Casdoor 会为该邮箱调用 sendMail,因此此项必填
    From name(可选)发件人显示名称
    Endpointhttps://graph.microsoft.com/v1.0。仅在国家级云环境中更改此设置,例如 https://graph.microsoft.us/v1.0
    Token URLhttps://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/token,需将 <tenant-id> 替换为 Directory (tenant) ID
    Scopehttps://graph.microsoft.com/.default
  4. 填写 Email title 和 Email content。请参阅 模板。Casdoor 将以 HTML 格式发送内容,并且不会在 Sent Items 中保留副本。

  5. 保存提供商.

Enable proxy 会通过 Casdoor 的 SOCKS5 代理发送令牌请求和 API 调用。请参阅 代理。

验证结果​

  1. 点击 Test SMTP Connection。对于此类型,Casdoor 仅获取令牌,这会检查令牌 URL、客户端 ID 和客户端密钥,而不会发送邮件。
  2. 点击 Send Testing Email 并检查消息是否到达 Test Email 邮箱。

然后将提供商添加到你的应用中。参见 Add providers to an application。

故障排除​

ErrorCause
the token URL of the Microsoft Graph email provider is requiredToken URL 为空或仍包含 <tenant-id>
the from address of the Microsoft Graph email provider must be the mailbox that sends the emailsFrom address 为空或不是电子邮件地址
oauth2: cannot fetch token 伴随 AADSTS 代码Microsoft Entra ID 拒绝了令牌请求。请检查 Token URL 中的租户 ID、Client ID 和 Client secret。注意 Client secret 必须是密钥的值而非其 ID,且未过期
Microsoft Graph sendMail failed with status 403该应用没有经过管理员同意的 Mail.Send 应用程序权限,或者访问策略不允许其以 From address 的身份发送邮件
Microsoft Graph sendMail failed with status 404From address 不是租户中的邮箱

另请参阅​