跳到主要内容

使用 SendGrid Email 设置电子邮件验证

Logto 官方的 SendGrid 电子邮件服务连接器。

提示:

本指南假设你对 Logto 连接器 (Connectors) 有基本的了解。对于不熟悉的人,请参考 连接器 (Connectors) 指南以开始了解。

开始使用​

SendGrid(即 Twilio SendGrid)是一个用于事务性和营销电子邮件的客户通信平台。我们可以使用其电子邮件发送功能来发送验证码。

注册 SendGrid 账户​

在 SendGrid 网站创建一个新账户。如果你已经有账户,可以跳过此步骤。

验证发件人​

前往 SendGrid 控制台页面并使用你的 SendGrid 账户登录。

发件人表示我们将从哪个地址发送验证码邮件。为了通过 SendGrid 邮件服务器发送邮件,你需要至少验证一个发件人。

从 SendGrid 控制台页面开始,进入侧边栏的“Settings” -> “Sender Authentication”。

推荐进行域认证,但不是强制的。你可以点击“Authenticate Your Domain”卡片中的“Get started”,并按照接下来的指南将发件人链接并验证到 SendGrid。

通过点击面板中的“Verify a Single Sender”按钮,你现在需要填写一些关键信息来创建一个发件人。按照指南填写所有这些字段,然后点击“Create”按钮。

创建单个发件人后,会向你的发件人邮箱地址发送一封带有验证链接的邮件。进入你的邮箱,找到验证邮件,并通过点击邮件中提供的链接完成单个发件人的验证。现在,你可以使用刚刚验证的发件人通过 SendGrid 连接器发送邮件。

创建 API 密钥​

从 SendGrid 控制台页面开始,进入侧边栏的“Settings” -> “API Keys”。

点击 API Keys 页面右上角的“Create API Key”。输入 API 密钥的名称,并根据你的使用场景自定义“API Key Permission”。在使用此 API 密钥发送邮件之前,需要全局 Full Access 或 Restricted Access 并对 Mail Send 具有完全访问权限。

在完成 Create API Key 过程后,API 密钥会显示在屏幕上。你应该将此 API 密钥保存在安全的地方,因为这是你唯一能看到它的机会。

配置你的连接器​

在“创建 API 密钥”部分中创建的 API Key 填写到 apiKey 字段中。

在 fromEmail 和 fromName 字段中填写发件人的 From Address 和 Nickname。你可以在 "Sender Management" 页面找到发件人的详细信息。fromName 是可选的,所以你可以跳过填写。

你可以为不同的情况添加多个 SendGrid 邮件连接器模板。以下是添加单个模板的示例:

  • 填写 subject 字段,作为邮件的标题。
  • 用任意字符串类型的内容填写 content 字段。不要忘记保留 {{code}} 占位符用于随机验证码。
  • 根据不同的使用场景填写 usageType 字段,可以是 Register、SignIn、ForgotPassword、Generic。
  • 根据不同的内容类型填写 type 字段,可以是 text/plain 或 text/html。

为了启用完整的用户流程,需要使用 Register、SignIn、ForgotPassword 和 Generic 的模板。

以下是 SendGrid 连接器模板 JSON 的示例。

[
{
"subject": "<register-template-subject>",
"content": "<Logto: Your verification code is {{code}}. (register template)>",
"usageType": "Register",
"type": "text/plain",
},
{
"subject": "<sign-in-template-subject>",
"content": "<Logto: Your verification code is {{code}}. (sign-in template)>",
"usageType": "SignIn",
"type": "text/plain",
},
{
"subject": "<forgot-password-template-subject>",
"content": "<Logto: Your verification code is {{code}}. (forgot-password template)>",
"usageType": "ForgotPassword",
"type": "text/plain",
},
{
"subject": "<generic-template-subject>",
"content": "<Logto: Your verification code is {{code}}. (generic template)>",
"usageType": "Generic",
"type": "text/plain",
},
]

测试 SendGrid 邮件连接器​

你可以输入一个电子邮件地址并点击“Send”来查看设置是否可以在“Save and Done”之前工作。

就是这样。不要忘记 在登录体验中启用连接器。

配置类型​

名称类型
apiKeystring
fromEmailstring
fromNamestring (可选)
templatesTemplate[]
模板属性类型枚举值
subjectstringN/A
contentstringN/A
usageTypeenum string'Register' | 'SignIn' | 'ForgotPassword' | 'Generic'
typeenum string'text/plain' | 'text/html'