通过您自己的 HTTP API 发送邮件
本指南介绍如何通过您描述的 HTTP 端点发送 Casdoor 的电子邮件(例如验证码和密码重置链接)。适用于没有内置类型的电子邮件服务,或者用于构建和发送邮件的自有服务。
学习目标
- 在 Casdoor 中描述您的电子邮件服务的 HTTP 请求。
- 了解 Casdoor 如何构建请求。
所需条件
- 具有 HTTP API 并在成功时返回 HTTP 200 的电子邮件服务或 webhook
- 管理员访问 Casdoor 管理控制台
在 Casdoor 中添加提供商
-
在 Casdoor 管理控制台中,前往 Identity > Providers 并添加一个提供商。
-
将 Category 设置为
Email,将 Type 设置为Custom HTTP Email。 -
填写字段:
Field Description From address Email address of the sender From name Name of the sender. If empty, Casdoor uses the display name of the organization Endpoint URL of your API. The default is https://example.com/send-custom-http-emailMethod GET,POST(default),PUT, orDELETEContent type For methods other than GET:application/x-www-form-urlencoded(default) orapplication/jsonHTTP header Extra request headers, such as an Authorizationheader with your API key. Enter each header as a row of Keys and ValuesHTTP body mapping For methods other than GET: the field names of the request. See Field names -
编写 Email title 和 Email content。参见 模板。
-
保存提供商并将其添加到您的应用。参见 向应用添加提供商。
该页面还显示 Host、Port、SSL mode、Enable proxy 和 Test SMTP Connection。Custom HTTP Email 提供商不使用这些字段。
Casdoor 如何构建请求
字段名称
请求包含以下字段。在 HTTP body mapping 中,您可以将它们重命名为您的 API 所期望的名称。映射的每一行都需要一个值。
| Row | Default field name | Value |
|---|---|---|
| From name | fromName | From name |
| From address | fromAddress | From address |
| To address | toAddress | The recipient |
| Subject | subject | Email title |
| Email content | content | Email 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:
| Field | Value |
|---|---|
| Endpoint | https://mail.example.com/api/send |
| Method | POST |
| Content type | application/x-www-form-urlencoded |
| HTTP header | Authorization: Bearer <your-api-key> |
| HTTP body mapping | From address: from, To address: to, Subject: subject, Email content: html |
<your-api-key> 是您电子邮件服务的 API 密钥。
验证结果
- 保存提供商.
- 在 Test Email 中输入一个地址,然后单击 Send Testing Email。您的 API 将收到请求。