电子邮件
Page summary:
电子邮件功能通过本地 SMTP 或外部提供商(如 SendGrid)发送事务信息。本文档中的设置指南涵盖提供商配置以及通过控制器或钩子扩展发送方式。
电子邮件功能使 Strapi 应用能够从服务器或外部提供商发送电子邮件。
🌐 The Email feature enables Strapi applications to send emails from a server or an external provider.
配置
🌐 Configuration
电子邮件功能的大多数配置选项通过你的 Strapi 项目代码进行处理。管理面板提供了当前配置、连接状态和提供商功能的只读视图,并允许用户发送测试电子邮件。
🌐 Most configuration options for the Email feature are handled via your Strapi project's code. The admin panel provides a read-only view of the current configuration, connection status, and provider capabilities, and lets users send a test email.
- 电子邮件提供商指的是 Strapi 用来发送电子邮件的包(例如官方提供商如 Sendgrid 或社区包如
@strapi/provider-email-nodemailer)。当 Strapi 调用它们时,提供商实现发送邮件的逻辑。 - 提供商主机(或服务器)是指提供商公开的连接详细信息(例如 SMTP 主机名、端口或 REST API 端点)。一些提供商将这些详细信息隐藏在 API 密钥后面,而另一些则要求你在配置中提供与主机相关的选项。
电子邮件功能仅处理外发投递。接收或解析传入的消息不在内置插件的范围内,必须通过你的电子邮件提供商的入站 Webhook 或自定义集成来实现。
🌐 The Email feature only handles outbound delivery. Receiving or parsing incoming messages is outside the scope of the built-in plugin and must be implemented with your email provider's inbound webhooks or a custom integration.
管理面板设置
🌐 Admin panel settings
配置此功能的路径: 设置 > 邮件功能 > 配置

大多数字段的配置界面是只读的。它显示当前的 提供程序配置,并允许用户测试连接性。
🌐 The Configuration interface is read-only for most fields. It displays the current provider configuration and lets users test connectivity.
以下信息显示在配置面板中:
🌐 The following information is shown in the Configuration panel:
- 默认发送者邮箱,如果配置的
defaultFrom地址包含显示名称,则为 默认发送者名称。 - 默认回复邮件,如果配置的
defaultReplyTo地址包含显示名称,默认回复名称。 - 电子邮件提供商:当前使用的提供商。
如果活动提供程序支持 SMTP 连接验证(例如,Nodemailer 提供程序),还会显示一个 连接状态 字段,并带有 测试连接 按钮。点击它可以在不发送消息的情况下验证 SMTP 连接。根据结果,该按钮会显示 已连接 或 错误 徽章。
🌐 If the active provider supports SMTP connection verification (for example, the Nodemailer provider), a Connection status field is also shown with a Test connection button. Clicking it verifies the SMTP connection without sending a message. The button displays a Connected or Error badge depending on the result.
当活动提供商公开 SMTP 元数据时,提供商功能 卡片会出现在主配置下方。它显示 SMTP 服务器地址、加密协议(TLS、STARTTLS 或无)、身份验证类型和用户、池状态(启用连接池时为空闲或活动),以及已启用 功能的徽章,如 DKIM、OAuth2、速率限制和连接池。
🌐 A Provider capabilities card appears below the main configuration when the active provider exposes SMTP metadata. It shows the SMTP server address, encryption protocol (TLS, STARTTLS, or None), authentication type and user, pool status (Idle or Active, when connection pooling is enabled), and badges for enabled features such as DKIM, OAuth2, rate limiting, and connection pool.
此页面上唯一可由用户编辑的字段是 测试邮件发送 下的 收件人邮箱 字段。一个 发送测试邮件 按钮会向该地址发送测试邮件。
🌐 The only user-editable field on this page is the Recipient email field under Test email delivery. A Send test email button sends a test message to that address.
仅当当前角色启用了“访问电子邮件设置页面”权限时,此页面才可见(有关更多信息,请参见RBAC 功能文档):
🌐 This page is only visible if the current role has the "Access the Email Settings page" permission enabled (see RBAC feature documentation for more information):

基于代码的配置
🌐 Code-based configuration
电子邮件功能需要在 config/plugins.js|ts 文件中配置提供者及其设置。有关详细的安装和配置说明,请参见 providers。
🌐 The Email feature requires a provider and a provider configuration in the config/plugins.js|ts file. See providers for detailed installation and configuration instructions.
Sendmail 是 Strapi 邮件功能中的默认邮件提供商。它为本地开发环境提供功能,但在默认配置下不适合生产使用。对于生产阶段的应用,你需要进一步配置 Sendmail 或更换提供商。
电子邮件配置选项
🌐 Email configuration options
插件配置在 config/plugins.js 文件或 config/plugins.ts 文件中定义。请参阅 providers 以获取详细的特定提供程序的安装和配置说明。
🌐 Plugins configuration are defined in the config/plugins.js file or config/plugins.ts file. Please refer to providers for detailed provider-specific installation and configuration instructions.
| 选项 | 类型 | 描述 | 默认值 | 备注 |
|---|---|---|---|---|
provider | string | 要使用的电子邮件提供商。 | sendmail | 必填 |
providerOptions | object | 电子邮件提供商选项。 | {} | 可选 |
providerOptions.apiKey | string | 邮件提供商的 API 密钥。 | '' | 可选 |
settings | object | 邮件设置。 | {} | 可选 |
settings.defaultFrom | string | 用作发件人的默认电子邮件地址。 | '' | 可选 |
settings.defaultReplyTo | string | 用作回复地址的默认电子邮件地址。 | '' | 可选 |
ratelimit | object | 邮件速率限制设置。 | {} | 可选 |
ratelimit.enabled | boolean | 是否启用速率限制。 | true | 可选 |
ratelimit.interval | string | 限流间隔(分钟)。 | 5 | 可选 |
ratelimit.max | number | 在该时间间隔内允许的最大请求数。 | 5 | 可选 |
ratelimit.delayAfter | number | 应用速率限制之前允许的请求数量。 | 1 | 可选 |
ratelimit.timeWait | number | 响应请求前等待的时间(毫秒)。 | 1 | 可选 |
ratelimit.prefixKey | string | 限流键的前缀。 | ${userEmail} | 可选 |
ratelimit.whitelist | array(string) | 要从速率限制中列入白名单的 IP 地址数组。 | [] | 可选 |
ratelimit.store | object | 限流存储位置,更多信息请参见 koa2-ratelimit documentation。 | MemoryStore | 可选 |
提供者
🌐 Providers
电子邮件功能可以通过安装和配置其他提供程序来扩展。
🌐 The Email feature can be extended via the installation and configuration of additional providers.
提供商为插件的核心功能添加了扩展,例如,使用 Amazon SES 而不是 Sendmail 来发送电子邮件。
🌐 Providers add an extension to the core capabilities of the plugin, for example to use Amazon SES for emails instead of Sendmail.
Strapi 既有官方提供的供应商——可通过 Marketplace 发现——也有许多由社区维护的供应商,可通过 npm 获取。
安装提供程序
🌐 Installing providers
新的提供程序可以使用 npm 或 yarn 安装,格式如下 @strapi/provider-<plugin>-<provider> --save。
例如,要安装 Sendgrid 提供程序:
🌐 For example, to install the Sendgrid provider:
- Yarn
- NPM
yarn add @strapi/provider-email-sendgrid
npm install @strapi/provider-email-sendgrid --save
配置提供者
🌐 Configuring providers
新安装的提供程序已在 “/config/plugins” 文件 中启用并配置。如果该文件不存在,你必须创建它。
🌐 Newly installed providers are enabled and configured in the /config/plugins file. If this file does not exist you must create it.
- 每个提供商将拥有不同的配置设置。请查看该提供商在 Marketplace 或 npm 的相关条目 以了解更多信息。
- 对于使用 Nodemailer 提供程序的生产场景(OAuth2、连接池、DKIM 签名、速率限制),请参阅专用文档。
以下是 Sendgrid 提供商的示例配置:
🌐 The following is an example configuration for the Sendgrid provider:
- JavaScript
- TypeScript
module.exports = ({ env }) => ({
// ...
email: {
config: {
provider: 'sendgrid', // For community providers pass the full package name (e.g. provider: 'strapi-provider-email-mandrill')
providerOptions: {
apiKey: env('SENDGRID_API_KEY'),
},
settings: {
defaultFrom: 'juliasedefdjian@strapi.io',
defaultReplyTo: 'juliasedefdjian@strapi.io',
testAddress: 'juliasedefdjian@strapi.io',
},
},
},
// ...
});
export default ({ env }) => ({
// ...
email: {
config: {
provider: 'sendgrid', // For community providers pass the full package name (e.g. provider: 'strapi-provider-email-mandrill')
providerOptions: {
apiKey: env('SENDGRID_API_KEY'),
},
settings: {
defaultFrom: 'juliasedefdjian@strapi.io',
defaultReplyTo: 'juliasedefdjian@strapi.io',
testAddress: 'juliasedefdjian@strapi.io',
},
},
},
// ...
});
- 在每个环境使用不同的提供者时,请在
/config/env/${yourEnvironment}/plugins.js|ts中指定正确的配置(参见 Environments)。 - 一次只能激活一个电子邮件提供商。如果 Strapi 没有识别电子 邮件提供商设置,请确认
plugins.js|ts文件在正确的文件夹中。 - 在使用 Strapi 设置期间创建的两个电子邮件模板测试新的电子邮件提供商时,模板上的 发件人邮箱 默认为
no-reply@strapi.io,需要根据你的电子邮件提供商进行更新,否则测试将失败(请参见 本地配置模板)。 - 为了获得最佳的邮件送达率,请与你的电子邮件提供商配置 SPF/DKIM,并确保
defaultFrom域与你在提供商处验证的域一致。
每环境配置
🌐 Per-environment configuration
在配置你的提供者时,你可能希望根据 NODE_ENV 环境变量更改配置,或使用特定环境的凭据。
🌐 When configuring your provider you might want to change the configuration based on the NODE_ENV environment variable or use environment specific credentials.
你可以在 /config/env/{env}/plugins.js|ts 配置文件中设置特定配置,它将用于覆盖默认配置。
🌐 You can set a specific configuration in the /config/env/{env}/plugins.js|ts configuration file and it will be used to overwrite the default configuration.
有些提供商会暴露 SMTP 风格的连接详情,而不是(或除了)API 密钥。在 providerOptions 中添加这些值,以便 Strapi 可以访问提供商主机。例如,社区版 Nodemailer 提供商需要主机、端口和认证凭据:
🌐 Some providers expose SMTP-style connection details instead of (or in addition to) an API key. Add those values in providerOptions so Strapi can reach the provider host. For instance, the community Nodemailer provider expects the host, port, and authentication credentials:
- JavaScript
- TypeScript
module.exports = ({ env }) => ({
email: {
config: {
provider: 'nodemailer',
providerOptions: {
host: env('SMTP_HOST'),
port: env.int('SMTP_PORT', 587),
secure: false, // Use `true` for port 465
auth: {
user: env('SMTP_USERNAME'),
pass: env('SMTP_PASSWORD'),
},
},
settings: {
defaultFrom: 'no-reply@example.com',
defaultReplyTo: 'support@example.com',
},
},
},
});
export default ({ env }) => ({
email: {
config: {
provider: 'nodemailer',
providerOptions: {
host: env('SMTP_HOST'),
port: 587,
secure: false, // Use `true` for port 465
auth: {
user: env('SMTP_USERNAME'),
pass: env('SMTP_PASSWORD'),
},
},
settings: {
defaultFrom: 'no-reply@example.com',
defaultReplyTo: 'support@example.com',
},
},
},
});
如果你的提供商给你的是单个 URL 而不是主机和端口值,请在 providerOptions 中使用该 URL(例如 https://api.eu.mailgun.net),使用该包所期望的键。
🌐 If your provider gives you a single URL instead of host and port values, pass that URL (for example https://api.eu.mailgun.net) in providerOptions using the key the package expects.
构建自定义提供程序
🌐 Building a custom provider
要构建你自己的提供者,将其发布到 npm,或在你的项目中本地使用,请参阅专门的文档:
🌐 To build your own provider, publish it to npm, or use it locally in your project, see the dedicated documentation:
使用
🌐 Usage
电子邮件功能使用 Strapi 全局 API,这意味着它可以在 Strapi 应用的任何地方调用,无论是通过后台服务器本身的 控制器或服务 还是从管理面板,例如响应某个事件时(使用 生命周期钩子)。
🌐 The Email feature uses the Strapi global API, meaning it can be called from anywhere inside a Strapi application, either from the back-end server itself through a controller or service, or from the admin panel, for example in response to an event (using lifecycle hooks).
使用控制器或服务发送电子邮件
🌐 Sending emails with a controller or service
电子邮件功能有一个 email 服务,其中包含 2 个发送电子邮件的功能:
🌐 The Email feature has an email service that contains 2 functions to send emails:
send()直接包含电子邮件内容,sendTemplatedEmail()从内容管理器获取数据以填充电子邮件,从而简化程序化电子邮件的流程。
使用 send() 函数
🌐 Using the send() function
要在用户操作后触发电子邮件,请将 send() 函数添加到 控制器 或 服务。发送函数具有以下属性:
🌐 To trigger an email in response to a user action add the send() function to a controller or service. The send function has the following properties:
| 属性 | 类型 | 描述 |
|---|---|---|
from | string(电子邮件地址) | 发件人地址。如果未指定,将使用来自 plugins.js 的 defaultFrom。 |
to | string(电子邮件地址) | 收件人地址。必填。 |
cc | string(电子邮件地址) | 抄送收件人。可选。 |
bcc | string(电子邮件地址) | 密送收件人。可选。 |
replyTo | string(电子邮件地址) | 回复地址。如果未指定,则使用 plugins.js 中的 defaultReplyTo。 |
subject | string | 电子邮件主题。必填。 |
text | string | 纯文本正文。需要 text 或 html 中的一个。 |
html | string | HTML 正文。必须提供 text 或 html。 |
attachments | object[] | 附件对象数组。 |
headers | object | 自定义 SMTP 头,例如 { 'X-Custom-Header': 'value' }。 |
priority | 'high' | 'normal' | 'low' | 邮件优先级标志。 |
inReplyTo | string | 被回复邮件的消息ID。用于会话线程。 |
references | string | string[] | 此电子邮件引用的消息 ID 列表。用于对话线程。 |
envelope | object | 带有 from 和 to 字段的自定义 SMTP 信封。用于退信处理。 |
list | object | RFC 2369 列表-* 头。支持在 Gmail 和 Outlook 中一键退订新闻通讯。 |
icalEvent | object | 以 iCalendar 格式的日历事件邀请。附加 { method, content }。 |
dsn | object | 传递状态通知设置。请求退回或传递确认报告。 |
Nodemailer 提供程序对所有 send() 字段使用显式允许列表。未知属性会被静默丢弃。有关支持字段的完整列表 —— 包括 dkim、amp、raw、auth(每条消息的 OAuth2) 以及其他字段 —— 请参见 provider README on npm。
🌐 The Nodemailer provider uses an explicit allowlist for all send() fields. Unknown properties are silently dropped. For the complete list of supported fields — including dkim, amp, raw, auth (per-message OAuth2), and others — see the provider README on npm.
以下代码示例可用于控制器或服务:
🌐 The following code example can be used in a controller or a service:
await strapi.plugins['email'].services.email.send({
to: 'valid email address',
from: 'your verified email address', //e.g. single sender verification in SendGrid
cc: 'valid email address',
bcc: 'valid email address',
replyTo: 'valid email address',
subject: 'The Strapi Email feature worked successfully',
text: 'Hello world!',
html: 'Hello world!',
}),
使用 sendTemplatedEmail() 函数
🌐 Using the sendTemplatedEmail() function
sendTemplatedEmail() 函数用于从模板撰写电子邮件。该函数从可用属性中编译电子邮件,然后发送电子邮件。
🌐 The sendTemplatedEmail() function is used to compose emails from a template. The function compiles the email from the available properties and then sends the email.
要使用 sendTemplatedEmail() 函数,定义 emailTemplate 对象并将该函数添加到控制器或服务中。该函数调用 emailTemplate 对象,并且可选择调用 emailOptions 和 data 对象:
🌐 To use the sendTemplatedEmail() function, define the emailTemplate object and add the function to a controller or service. The function calls the emailTemplate object, and can optionally call the emailOptions and data objects:
| 参数 | 描述 | 类型 | 默认值 ||-----------------|--------------------------------------------------------------------------------------------------------------------------------------------|----------|---------|| emailOptions
可选 | 包含电子邮件地址属性:to、from、replyTo、cc 和 bcc | object | || emailTemplate | 包含电子邮件内容属性:使用 subject、text 和 html Lodash string templates | object | || data
可选 | 包含用于编译模板的数据 | object | |
以下代码示例可用于控制器或服务:
🌐 The following code example can be used in a controller or a service:
const emailTemplate = {
subject: 'Welcome <%= user.firstname %>',
text: `Welcome to mywebsite.fr!
Your account is now linked with: <%= user.email %>.`,
html: `<h1>Welcome to mywebsite.fr!</h1>
<p>Your account is now linked with: <%= user.email %>.<p>`,
};
await strapi.plugins['email'].services.email.sendTemplatedEmail(
{
to: user.email,
// from: is not specified, the defaultFrom is used.
},
emailTemplate,
{
user: _.pick(user, ['username', 'email', 'firstname', 'lastname']),
}
);
从生命周期钩子发送电子邮件
🌐 Sending emails from a lifecycle hook
要根据管理员在管理面板中的操作触发电子邮件,请使用 生命周期钩子 和 send() 函数。
🌐 To trigger an email based on administrator actions in the admin panel use lifecycle hooks and the send() function.
以下示例说明了如何在内容管理器中每次添加新内容条目时使用 afterCreate 生命周期钩子发送电子邮件:
🌐 The following example illustrates how to send an email each time a new content entry is added in the Content Manager use the afterCreate lifecycle hook:
- JavaScript
- TypeScript
module.exports = {
async afterCreate(event) { // Connected to "Save" button in admin panel
const { result } = event;
try{
await strapi.plugin('email').service('email').send({ // you could also do: await strapi.service('plugin:email.email').send({
to: 'valid email address',
from: 'your verified email address', // e.g. single sender verification in SendGrid
cc: 'valid email address',
bcc: 'valid email address',
replyTo: 'valid email address',
subject: 'The Strapi Email feature worked successfully',
text: '${fieldName}', // Replace with a valid field ID
html: 'Hello world!',
})
} catch(err) {
console.log(err);
}
}
}
export default {
async afterCreate(event) { // Connected to "Save" button in admin panel
const { result } = event;
try{
await strapi.plugins['email'].services.email.send({
to: 'valid email address',
from: 'your verified email address', // e.g. single sender verification in SendGrid
cc: 'valid email address',
bcc: 'valid email address',
replyTo: 'valid email address',
subject: 'The Strapi Email feature worked successfully',
text: '${fieldName}', // Replace with a valid field ID
html: 'Hello world!',
})
} catch(err) {
console.log(err);
}
}
}