Skip to main content

电子邮件

¥Email

电子邮件功能使 Strapi 应用能够从服务器或外部提供商发送电子邮件。

¥The Email feature enables Strapi applications to send emails from a server or an external provider.

IDENTITY CARD
Plan
Free feature
Role & permission
Email > "send" permission for the user to send emails via the backend server
Activation
Available by default
Environment
Available in both Development & Production environment

配置

¥Configuration

电子邮件功能的大多数配置选项都通过你的 Strapi 项目的代码处理。电子邮件功能无法在管理面板中配置,但是如果管理员已设置电子邮件,用户可以测试电子邮件传递。

¥Most configuration options for the Email feature are handled via your Strapi project's code. The Email feature is not configurable in the admin panel, however users can test email delivery if it has been setup by an administrator.

管理面板设置

¥Admin panel settings

配置功能的路径: 设置 > 电子邮件功能 > 配置

¥Path to configure the feature: Settings > Email feature > Configuration

Email configurationEmail configuration

在配置界面中,只有 "测试电子邮件传递" 下的电子邮件地址字段可供用户修改。发送测试电子邮件按钮可发送测试电子邮件。

¥In the Configuration interface, only the email address field under "Test email delivery" is modifiable by users. A Send test email button sends a test email.

此页面仅在当前角色启用了 "访问电子邮件设置页面" 权限时可见(有关更多信息,请参阅 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):

Email configurationEmail configuration

基于代码的配置

¥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.

发送邮件 是 Strapi 电子邮件功能中的默认电子邮件提供商。它为本地开发环境提供功能,但在默认配置中不适合生产。对于生产阶段应用,你需要进一步配置 Sendmail 或更改提供商。

¥Sendmail is the default email provider in the Strapi Email feature. It provides functionality for the local development environment but is not production-ready in the default configuration. For production stage applications you need to further configure Sendmail or change providers.

电子邮件配置选项

¥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.

选项类型描述默认值注意
providerstring要使用的电子邮件提供商。sendmail必需的
providerOptionsobject电子邮件提供商选项。{}可选的
providerOptions.apiKeystring电子邮件提供商的 API 密钥。''可选的
settingsobject电子邮件设置。{}可选的
settings.defaultFromstring用作发件人的默认电子邮件地址。''可选的
settings.defaultReplyTostring用作回复地址的默认电子邮件地址。''可选的
ratelimitobject电子邮件速率限制设置。{}可选的
ratelimit.enabledboolean是否启用速率限制。true可选的
ratelimit.intervalstring速率限制的间隔(分钟)。5可选的
ratelimit.maxnumber间隔内允许的最大请求数。5可选的
ratelimit.delayAfternumber应用速率限制之前允许的请求数。1可选的
ratelimit.timeWaitnumber响应请求之前等待的时间(以毫秒为单位)。1可选的
ratelimit.prefixKeystring速率限制键的前缀。${userEmail}可选的
ratelimit.whitelistarray(string)要从速率限制中列入白名单的 IP 地址数组。[]可选的
ratelimit.storeobject速率限制存储位置,有关更多信息,请参阅 koa2-ratelimit 文档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 维护的官方提供程序(可通过 市场 找到)以及许多社区维护的提供程序(可通过 npm 获取)。

¥There are both official providers maintained by Strapi — discoverable via the Marketplace — and many community maintained providers available via npm.

可以将提供程序配置为 private,以确保对资源 URL 进行签名以实现安全访问。

¥A provider can be configured to be private to ensure asset URLs will be signed for secure access.

安装提供程序

¥Installing providers

可以使用 npmyarn 使用以下格式 @strapi/provider-<plugin>-<provider> --save 安装新的提供程序。

¥New providers can be installed using npm or yarn using the following format @strapi/provider-<plugin>-<provider> --save.

例如,要安装 Sendgrid 提供程序:

¥For example, to install the Sendgrid provider:

yarn add @strapi/provider-email-sendgrid
配置提供者

¥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.

每个提供者都有不同的可用配置设置。查看 市场npm 中该提供商的相应条目以了解更多信息。

¥Each provider will have different configuration settings available. Review the respective entry for that provider in the Marketplace or npm to learn more.

以下是 Sendgrid 提供商的示例配置:

¥The following is an example configuration for the Sendgrid provider:

/config/plugins.js

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',
},
},
},
// ...
});
注意
  • 当每个环境使用不同的提供程序时,请在 /config/env/${yourEnvironment}/plugins.js|ts 中指定正确的配置(请参阅 环境)。

    ¥When using a different provider per environment, specify the correct configuration in /config/env/${yourEnvironment}/plugins.js|ts (See Environments).

  • 一次只有一个电子邮件提供者处于活动状态。如果 Strapi 未选择电子邮件提供者设置,请验证 plugins.js|ts 文件是否位于正确的文件夹中。

    ¥Only one email provider will be active at a time. If the email provider setting isn't picked up by Strapi, verify the plugins.js|ts file is in the correct folder.

  • 使用在 Strapi 设置期间创建的两个电子邮件模板测试新电子邮件提供者时,模板上的发送者电子邮件默认为 no-reply@strapi.io,需要根据你的电子邮件提供者进行更新,否则将无法通过测试(请参阅 本地配置模板)。

    ¥When testing the new email provider with those two email templates created during strapi setup, the shipper email on the template defaults to no-reply@strapi.io and needs to be updated according to your email provider, otherwise it will fail the test (See Configure templates locally).

每个环境的配置

¥Configuration per environment

配置提供程序时,你可能希望根据 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.

创建提供者

¥Creating providers

要实现你自己的自定义提供程序,你必须 创建 Node.js 模块

¥To implement your own custom provider you must create a Node.js module.

必须导出的接口取决于你为其开发提供程序的插件。以下是电子邮件功能的模板:

¥The interface that must be exported depends on the plugin you are developing the provider for. The following is a template for the Email feature:

module.exports = {
init: (providerOptions = {}, settings = {}) => {
return {
send: async options => {},
};
},
};

在发送功能中,你将可以访问:

¥In the send function you will have access to:

  • providerOptions 包含用 plugins.js|ts 编写的配置

    ¥providerOptions that contains configurations written in plugins.js|ts

  • settings 包含用 plugins.js|ts 编写的配置

    ¥settings that contains configurations written in plugins.js|ts

  • options 包含你从电子邮件插件服务调用发送函数时发送的选项

    ¥options that contains options you send when you call the send function from the email plugin service

你可以查看 Strapi 维护的提供商 以了解示例实现。

¥You can review the Strapi-maintained providers for example implementations.

创建新提供商后,你可以 发布到 npm 与社区共享,或仅为你的项目共享 在本地使用它

¥After creating your new provider you can publish it to npm to share with the community or use it locally for your project only.

本地提供者

¥Local providers

如果你想创建自己的提供程序而不将其发布到 npm 上,你可以按照以下步骤操作:

¥If you want to create your own provider without publishing it on npm you can follow these steps:

  1. 在你的应用中创建一个 providers 文件夹。

    ¥Create a providers folder in your application.

  2. 创建你的提供者(例如 /providers/strapi-provider-<plugin>-<provider>

    ¥Create your provider (e.g. /providers/strapi-provider-<plugin>-<provider>)

  3. 然后更新你的 package.json 以将你的 strapi-provider-<plugin>-<provider> 依赖链接到新提供商的 本地路径

    ¥Then update your package.json to link your strapi-provider-<plugin>-<provider> dependency to the local path of your new provider.

{
...
"dependencies": {
...
"strapi-provider-<plugin>-<provider>": "file:providers/strapi-provider-<plugin>-<provider>",
...
}
}
  1. /config/plugins.js|ts 文件更新为 配置提供者

    ¥Update your /config/plugins.js|ts file to configure the provider.

  2. 最后,运行 yarnnpm install 以安装新的自定义提供程序。

    ¥Finally, run yarn or npm install to install your new custom provider.

私有提供商

¥Private providers

你可以设置私有提供者,这意味着内容管理器中显示的每个资源 URL 都将经过签名以进行安全访问。

¥You can set up a private provider, meaning that every asset URL displayed in the Content Manager will be signed for secure access.

要启用私有提供程序,你必须实现 isPrivate() 方法并返回 true

¥To enable private providers, you must implement the isPrivate() method and return true.

在后端,Strapi 使用提供程序中实现的 getSignedUrl(file) 方法为每个资源生成签名 URL。签名的 URL 包含一个加密的签名,允许用户访问资源(但通常仅限于有限的时间和特定的限制,具体取决于提供者)。

¥In the backend, Strapi generates a signed URL for each asset using the getSignedUrl(file) method implemented in the provider. The signed URL includes an encrypted signature that allows the user to access the asset (but normally only for a limited time and with specific restrictions, depending on the provider).

请注意,出于安全原因,内容 API 将不会提供任何签名 URL。相反,使用 API 的开发者应该自己对 URL 进行签名。

¥Note that for security reasons, the content API will not provide any signed URLs. Instead, developers using the API should sign the urls themselves.

用法

¥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 service,其中包含 2 个发送电子邮件的功能:

¥The Email feature has an email service that contains 2 functions to send emails:

  • send() 直接包含电子邮件内容,

    ¥send() directly contains the email contents,

  • sendTemplatedEmail() 使用内容管理器中的数据来填充电子邮件,从而简化程序化电子邮件。

    ¥sendTemplatedEmail() consumes data from the Content Manager to populate emails, streamlining programmatic emails.

使用 send() 功能

¥Using the send() function

要触发电子邮件以响应用户操作,请将 send() 函数添加到 controllerservice。发送函数具有以下属性:

¥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:

属性类型格式描述
fromstring电子邮件地址如果未指定,则在 plugins.js 中使用 defaultFrom
tostring电子邮件地址必需的
ccstring电子邮件地址可选的
bccstring电子邮件地址可选的
replyTostring电子邮件地址可选的
subjectstring*必需的
textstring*需要 texthtml
htmlstring超文本标记语言需要 texthtml

以下代码示例可用于控制器或服务:

¥The following code example can be used in a controller or a service:

/src/api/my-api-name/controllers/my-api-name.ts|js (or /src/api/my-api-name/services/my-api-name.ts|js)
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 对象,并且可以选择调用 emailOptionsdata 对象:

¥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
可选
包含电子邮件寻址属性:tofromreplyToccbccobject
emailTemplate包含电子邮件内容属性:subjecttexthtml 使用 Lodash 字符串模板object
data
可选
包含用于编译模板的数据object

以下代码示例可用于控制器或服务:

¥The following code example can be used in a controller or a service:

/src/api/my-api-name/controllers/my-api-name.js (or ./src/api/my-api-name/services/my-api-name.js)


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:

/src/api/my-api-name/content-types/my-content-type-name/lifecycles.js

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);
}
}
}