メインコンテンツまでスキップ

メール(Email)

Page summary:

Email 機能は、ローカル SMTP や SendGrid などの外部プロバイダー経由でトランザクションメールを送信します。このページではプロバイダー設定と、コントローラー/フック経由で送信処理を拡張する方法を説明します。

Email 機能を使うと、Strapi アプリからサーバーまたは外部プロバイダー経由でメール送信できます。

IDENTITY CARD
Plan
無料で利用可能
ロールと権限
バックエンド経由で送信するには Email > "send" 権限
Activation
既定で利用可能
Environment
開発環境・本番環境の両方で利用可能

設定

Email 機能の設定の多くは Strapi プロジェクトのコード側で行います。管理パネルでは現在の設定、接続状態、プロバイダー機能を読み取り専用で確認でき、テストメール送信も実行できます。

プロバイダーとホストの違い
  • メールプロバイダーは、Strapi がメール送信時に呼び出すパッケージです(例: 公式の Sendgrid、コミュニティの @strapi/provider-email-nodemailer)。Strapi から呼ばれたときの送信ロジックを実装します。
  • プロバイダーホスト(サーバー)は、プロバイダーが公開する接続情報(SMTP ホスト名、ポート、REST API エンドポイントなど)を指します。API キーだけで隠蔽される場合もあれば、設定でホスト関連オプションの指定が必要な場合もあります。

Email 機能が扱うのは送信のみです。受信や受信メッセージ解析は組み込みプラグインの対象外で、プロバイダーの inbound webhook または独自連携で実装する必要があります。

管理パネル設定

設定の場所: Settings > Email feature > Configuration

Email configurationEmail configuration

Configuration 画面の大半は読み取り専用です。現在のプロバイダー設定を表示し、接続テストを実行できます。

Configuration パネルには次の情報が表示されます。

  • Default sender email と、defaultFrom に表示名が含まれる場合は Default sender name
  • Default response email と、defaultReplyTo に表示名が含まれる場合は Default reply-to name
  • Email provider: 現在使用中のプロバイダー。
Note

有効なプロバイダーが SMTP 接続検証に対応している場合(例: Nodemailer プロバイダー)、Connection statusTest connection ボタンが表示されます。クリックするとメール送信なしで SMTP 接続を検証し、結果に応じて Connected または Error バッジが表示されます。

有効なプロバイダーが SMTP メタデータを公開している場合は、メイン設定の下に Provider capabilities カードが表示されます。SMTP サーバーアドレス、暗号化方式(TLS / STARTTLS / None)、認証種別とユーザー、プール状態(接続プーリング有効時の Idle / Active)、DKIM・OAuth2・レート制限・接続プールなどの有効機能バッジを確認できます。

このページでユーザーが編集できるのは Test email deliveryRecipient email のみです。Send test email でその宛先へテストメールを送信します。

このページは、現在のロールに "Access the Email Settings page" 権限がある場合のみ表示されます(詳細は RBAC を参照)。

Email configurationEmail configuration

コードベース設定

Email 機能には config/plugins.js|ts でプロバイダーとその設定が必要です。導入・設定の詳細は プロバイダー を参照してください。

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.

メール設定オプション

プラグイン設定は config/plugins.js または config/plugins.ts で定義します。プロバイダー固有の導入・設定は プロバイダー を参照してください。

オプション説明既定値備考
providerstringThe email provider to use.sendmailRequired
providerOptionsobjectThe email provider options.{}オプションal
providerOptions.apiKeystringThe API key for the email provider.''オプションal
settingsobjectThe email settings.{}オプションal
settings.defaultFromstringThe default email address to use as the sender.''オプションal
settings.defaultReplyTostringThe default email address to use as the reply-to address.''オプションal
ratelimitobjectThe email rate limit settings.{}オプションal
ratelimit.enabledbooleanWhether to enable rate limiting.trueオプションal
ratelimit.intervalstringThe interval for rate limiting in minutes.5オプションal
ratelimit.maxnumberThe maximum number of requests allowed during the interval.5オプションal
ratelimit.delayAfternumberThe number of requests allowed before rate limiting is applied.1オプションal
ratelimit.timeWaitnumberTime to wait before responding to a request (in milliseconds).1オプションal
ratelimit.prefixKeystringThe prefix for the rate limit key.${userEmail}オプションal
ratelimit.whitelistarray(string)Array of IP addresses to whitelist from rate limiting.[]オプションal
ratelimit.storeobjectRate limiting storage location and for more information please see the koa2-ratelimit documentation.MemoryStoreオプションal

プロバイダー

Email 機能は追加プロバイダーの導入と設定で拡張できます。

プロバイダーによりプラグインの基本機能を拡張できます。例えば Sendmail の代わりに Amazon SES を使うことができます。

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

プロバイダーのインストール

新しいプロバイダーは npm または yarn@strapi/provider-<plugin>-<provider> --save 形式でインストールします。

例: Sendgrid プロバイダーをインストールする場合

yarn add @strapi/provider-email-sendgrid
プロバイダーの設定

Newly installed providers are enabled and configured in the /config/plugins file. If this file does not exist you must create it.

メールプロバイダー固有の設定
  • Each provider will have different configuration settings available. Review the respective entry for that provider in the Marketplace or npm to learn more.

  • For production scenarios with the Nodemailer provider (OAuth2, connection pooling, DKIM signing, rate limiting), see the dedicated documentation.

以下は Sendgrid プロバイダーの設定例です。

/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 に環境別設定を定義します(環境設定 参照)。
  • 同時に有効なのは 1 つのメールプロバイダーのみです。設定が反映されない場合は plugins.js|ts の配置先を確認してください。
  • Strapi セットアップ時に作成される 2 つのメールテンプレートで新プロバイダーを試す場合、テンプレートの shipper email は既定で no-reply@strapi.io です。プロバイダーに合わせて更新しないとテスト送信に失敗します(テンプレート設定 参照)。
  • 到達率を高めるには、プロバイダー側で SPF / DKIM を設定し、defaultFrom のドメインを検証済みドメインに合わせてください。
環境別設定

プロバイダー設定では、NODE_ENV に応じて設定を切り替えたり、環境ごとの資格情報を使い分けたりすることがあります。

/config/env/{env}/plugins.js|ts に環境別設定を書くと、既定設定を上書きできます。

一部プロバイダーは API キーの代わりに(または併用で)SMTP 形式の接続情報を要求します。Strapi がプロバイダーホストへ接続できるよう providerOptions に設定してください。例えばコミュニティ版 Nodemailer では host、port、認証情報が必要です。

/config/plugins.js
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',
},
},
},
});

プロバイダーが host / port の代わりに単一 URL を提供する場合は、パッケージが期待するキー名で providerOptions にその URL(例: https://api.eu.mailgun.net)を渡します。

カスタムプロバイダーの作成

独自プロバイダーを作成し npm 公開またはローカル利用する手順は次を参照してください。

使い方

Email 機能は Strapi のグローバル API を使うため、アプリ内のどこからでも呼び出せます。バックエンドの コントローラー/サービス 経由でも、管理パネルでのイベント応答(ライフサイクルフック)でも利用できます。

コントローラー/サービスでメール送信する

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

  • send() はメール内容を直接指定して送る
  • sendTemplatedEmail() は Content Manager のデータでテンプレートを埋め、プログラムからの送信を簡素化する

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:

プロパティ説明
fromstring (email address)Sender address. If not specified, uses defaultFrom from plugins.js.
tostring (email address)Recipient address. Required.
ccstring (email address)Carbon copy recipients. Optional.
bccstring (email address)Blind carbon copy recipients. Optional.
replyTostring (email address)Reply-to address. If not specified, uses defaultReplyTo from plugins.js.
subjectstringEmail subject. Required.
textstringPlain-text body. Either text or html is required.
htmlstringHTML body. Either text or html is required.
attachmentsobject[]Array of attachment objects.
headersobjectCustom SMTP headers, for example { 'X-Custom-Header': 'value' }.
priority'high' | 'normal' | 'low'Email priority flag.
inReplyTostringMessage-ID of the email being replied to. Used for conversation threading.
referencesstring | string[]Message-ID list this email references. Used for conversation threading.
envelopeobjectCustom SMTP envelope with from and to fields. Useful for bounce handling.
listobjectRFC 2369 List-* headers. Enables one-click unsubscribe in Gmail and Outlook for newsletters.
icalEventobjectCalendar event invitation in iCalendar format. Attach with { method, content }.
dsnobjectDelivery Status Notification settings. Requests bounce or delivery confirmation reports.
Nodemailer プロバイダー利用時

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.

次のコード例をコントローラーまたはサービスで利用できます。

/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() 関数を使う

sendTemplatedEmail() はテンプレートからメールを組み立てて送信する関数です。指定したプロパティから本文をコンパイルして送信します。

利用時は emailTemplate オブジェクトを定義し、コントローラーまたはサービスに関数を追加します。emailTemplate を必須で使い、emailOptionsdata は任意で渡せます。

パラメーター説明Default
emailOptions
Optional
Contains email addressing properties: to, from, replyTo, cc, and bccobject
emailTemplateContains email content properties: subject, text, and html using Lodash string templatesobject
data
Optional
Contains the data used to compile the templatesobject

次のコード例をコントローラーまたはサービスで利用できます。

/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']),
}
);

ライフサイクルフックからメール送信する

管理パネルでの管理者操作をトリガーに送信するには、ライフサイクルフックsend() 関数 を使います。

次の例は、Content Manager で新規エントリーが作成されるたびに afterCreate でメール送信する方法です。

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