跳到主内容

通过您自己的 HTTP API 发送邮件

本指南介绍如何通过您描述的 HTTP 端点发送 Casdoor 的电子邮件(例如验证码和密码重置链接)。适用于没有内置类型的电子邮件服务,或者用于构建和发送邮件的自有服务。


学习目标​

  • 在 Casdoor 中描述您的电子邮件服务的 HTTP 请求。
  • 了解 Casdoor 如何构建请求。

所需条件​

  • 具有 HTTP API 并在成功时返回 HTTP 200 的电子邮件服务或 webhook
  • 管理员访问 Casdoor 管理控制台

在 Casdoor 中添加提供商​

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

  2. 将 Category 设置为 Email,将 Type 设置为 Custom HTTP Email。

  3. 填写字段:

    FieldDescription
    From addressEmail address of the sender
    From nameName of the sender. If empty, Casdoor uses the display name of the organization
    EndpointURL of your API. The default is https://example.com/send-custom-http-email
    MethodGET, POST (default), PUT, or DELETE
    Content typeFor methods other than GET: application/x-www-form-urlencoded (default) or application/json
    HTTP headerExtra request headers, such as an Authorization header with your API key. Enter each header as a row of Keys and Values
    HTTP body mappingFor methods other than GET: the field names of the request. See Field names
  4. 编写 Email title 和 Email content。参见 模板。

  5. 保存提供商并将其添加到您的应用。参见 向应用添加提供商。

该页面还显示 Host、Port、SSL mode、Enable proxy 和 Test SMTP Connection。Custom HTTP Email 提供商不使用这些字段。

Casdoor 如何构建请求​

字段名称​

请求包含以下字段。在 HTTP body mapping 中,您可以将它们重命名为您的 API 所期望的名称。映射的每一行都需要一个值。

RowDefault field nameValue
From namefromNameFrom name
From addressfromAddressFrom address
To addresstoAddressThe recipient
SubjectsubjectEmail title
Email contentcontentEmail content, with the placeholders replaced

对于多个收件人,Casdoor 会为每个收件人发送一次 toAddresses 字段,而不是使用 toAddress。

方法和内容类型​

  • GET:Casdoor 将所有字段作为 Endpoint 的查询参数发送。
  • POST、PUT 或带有 application/x-www-form-urlencoded 的 DELETE:Casdoor 将所有字段作为正文中的表单字段发送。
  • POST、PUT 或带有 application/json 的 DELETE:Casdoor 发送一个包含发件人、主题和内容字段的 JSON 对象。
注意事项

在当前版本中,JSON 对象没有收件人字段。如果您的 API 需要在请求中包含收件人,请使用 application/x-www-form-urlencoded 或 GET。

Casdoor 将 HTTP header 中的头部添加到请求中。它将除 HTTP 200 以外的所有响应视为失败。

电子邮件的语言​

当 Casdoor 发送验证码或魔术链接时,它会添加一个 Accept-Language 头部,其中包含发起请求的浏览器的语言(以双字母代码表示,如 en 或 zh)。如果 HTTP header 中已经存在 Accept-Language 行,Casdoor 会保留该值。您的 API 可以使用此头部以用户的语言发送邮件,这也适用于注册码,即使用户尚未存在时 Casdoor 也会发送此类邮件。

示例​

接受包含 from、to、subject 和 html 字段的 POST 表单的 API:

FieldValue
Endpointhttps://mail.example.com/api/send
MethodPOST
Content typeapplication/x-www-form-urlencoded
HTTP headerAuthorization: Bearer <your-api-key>
HTTP body mappingFrom address: from, To address: to, Subject: subject, Email content: html

<your-api-key> 是您电子邮件服务的 API 密钥。

验证结果​

  1. 保存提供商.
  2. 在 Test Email 中输入一个地址,然后单击 Send Testing Email。您的 API 将收到请求。

另请参阅​