Readouble

Laravel 8.x メール

イントロダクションIntroduction

メールの送信は複雑である必要はありません。Laravelは、人気のあるSwiftMailerライブラリを利用したクリーンでシンプルなメールAPIを提供します。LaravelとSwiftMailerは、SMTP、Mailgun、Postmark、AmazonSES、およびsendmailを介して電子メールを送信するためのドライバーを提供し、選択したローカルまたはクラウドベースのサービスを介してメールの送信をすばやく開始できるようにします。Sending email doesn't have to be complicated. Laravel provides a clean, simple email API powered by the popular SwiftMailer[https://swiftmailer.symfony.com/] library. Laravel and SwiftMailer provide drivers for sending email via SMTP, Mailgun, Postmark, Amazon SES, and sendmail, allowing you to quickly get started sending mail through a local or cloud based service of your choice.

設定Configuration

Laravelのメールサービスは、アプリケーションのconfig/mail.php設定ファイルを介して設定できます。このファイル内で設定された各メーラーには、独自の設定と独自の「トランスポート」があり、アプリケーションがさまざまな電子メールサービスを使用して特定の電子メールメッセージを送信できるようにします。たとえば、アプリケーションでPostmarkを使用してトランザクションメールを送信し、AmazonSESを使用して一括メールを送信するなどです。Laravel's email services may be configured via your application's config/mail.php configuration file. Each mailer configured within this file may have its own unique configuration and even its own unique "transport", allowing your application to use different email services to send certain email messages. For example, your application might use Postmark to send transactional emails while using Amazon SES to send bulk emails.

mail設定ファイル内に、mailers設定配列があります。この配列には、Laravelがサポートしている主要なメールドライバ/トランスポートごとのサンプル設定エントリが含まれています。その中でdefault設定値は、アプリケーションが電子メールメッセージを送信する必要があるときにデフォルトで使用するメーラーを決定します。Within your mail configuration file, you will find a mailers configuration array. This array contains a sample configuration entry for each of the major mail drivers / transports supported by Laravel, while the default configuration value determines which mailer will be used by default when your application needs to send an email message.

ドライバ/トランスポートの前提条件Driver / Transport Prerequisites

MailgunやPostmarkなどのAPIベースのドライバは、多くの場合、SMTPサーバを介してメールを送信するよりも簡単で高速です。可能な限り、これらのドライバのいずれかを使用することを推奨します。すべてのAPIベースのドライバには、Composerパッケージマネージャーを介してインストールできるGuzzle HTTPライブラリが必要です。The API based drivers such as Mailgun and Postmark are often simpler and faster than sending mail via SMTP servers. Whenever possible, we recommend that you use one of these drivers. All of the API based drivers require the Guzzle HTTP library, which may be installed via the Composer package manager:

composer require guzzlehttp/guzzle

MailgunドライバMailgun Driver

Mailgunドライバを使用するには、最初にGuzzle HTTPライブラリをインストールします。次に、config/mail.php設定ファイルのdefaultオプションをmailgunに設定します。次に、config/services.php設定ファイルに次のオプションを確実に含めてください。To use the Mailgun driver, first install the Guzzle HTTP library. Then, set the default option in your config/mail.php configuration file to mailgun. Next, verify that your config/services.php configuration file contains the following options:

'mailgun' => [
    'domain' => env('MAILGUN_DOMAIN'),
    'secret' => env('MAILGUN_SECRET'),
],

米国のMailgunリージョンを使用していない場合は、services設定ファイルでリージョンのエンドポイントを定義できます。If you are not using the United States Mailgun region[https://documentation.mailgun.com/en/latest/api-intro.html#mailgun-regions], you may define your region's endpoint in the services configuration file:

'mailgun' => [
    'domain' => env('MAILGUN_DOMAIN'),
    'secret' => env('MAILGUN_SECRET'),
    'endpoint' => env('MAILGUN_ENDPOINT', 'api.eu.mailgun.net'),
],

PostmarkドライバPostmark Driver

Postmarkドライバを使用するには、Composerを介してPostmarkのSwiftMailerトランスポートをインストールします。To use the Postmark driver, install Postmark's SwiftMailer transport via Composer:

composer require wildbit/swiftmailer-postmark

次に、Guzzle HTTPライブラリをインストールし、config/mail.php設定ファイルのdefaultオプションをpostmarkに設定します。最後に、config/services.php設定ファイルに以下のオプションを確実に含めてください。Next, install the Guzzle HTTP library and set the default option in your config/mail.php configuration file to postmark. Finally, verify that your config/services.php configuration file contains the following options:

'postmark' => [
    'token' => env('POSTMARK_TOKEN'),
],

特定のメーラで使用する必要があるPostmarkメッセージストリームを指定したい場合は、message_stream_id設定オプションをメーラの設定配列に追加してください。この設定配列は、アプリケーションのconfig/mail.php設定ファイルにあります。If you would like to specify the Postmark message stream that should be used by a given mailer, you may add the message_stream_id configuration option to the mailer's configuration array. This configuration array can be found in your application's config/mail.php configuration file:

'postmark' => [
    'transport' => 'postmark',
    'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'),
],

この方法で、メッセージストリームが異なる複数のPostmarkメーラを設定することもできます。This way you are also able to set up multiple Postmark mailers with different message streams.

SESドライバSES Driver

Amazon SESドライバを使用するには、最初にAmazon AWS SDK for PHPをインストールする必要があります。このライブラリは、Composerパッケージマネージャーを介してインストールできます。To use the Amazon SES driver you must first install the Amazon AWS SDK for PHP. You may install this library via the Composer package manager:

composer require aws/aws-sdk-php

次に、config/mail.php設定ファイルのdefaultオプションをsesに設定し、config/services.php設定ファイルに以下のオプションを確実に含めてください。Next, set the default option in your config/mail.php configuration file to ses and verify that your config/services.php configuration file contains the following options:

'ses' => [
    'key' => env('AWS_ACCESS_KEY_ID'),
    'secret' => env('AWS_SECRET_ACCESS_KEY'),
    'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],

AWSの一時的な認証情報をセッショントークン経由で利用するには、アプリケーションのSES設定へtokenキーを追加します。To utilize AWS temporary credentials[https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html] via a session token, you may add a token key to your application's SES configuration:

'ses' => [
    'key' => env('AWS_ACCESS_KEY_ID'),
    'secret' => env('AWS_SECRET_ACCESS_KEY'),
    'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
    'token' => env('AWS_SESSION_TOKEN'),
],

メール送信時にAWS SDKのSendRawEmailメソッドへLaravelが渡すべき追加オプションを定義したい場合、ses設定内でoptions配列を定義してください。If you would like to define additional options[https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#sendrawemail] that Laravel should pass to the AWS SDK's SendRawEmail method when sending an email, you may define an options array within your ses configuration:

'ses' => [
    'key' => env('AWS_ACCESS_KEY_ID'),
    'secret' => env('AWS_SECRET_ACCESS_KEY'),
    'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
    'options' => [
        'ConfigurationSetName' => 'MyConfigurationSet',
        'Tags' => [
            ['Name' => 'foo', 'Value' => 'bar'],
        ],
    ],
],

フェイルオーバー設定Failover Configuration

アプリケーションのメールを送信するように設定した外部サービスがダウンすることがあります。このような場合には、プライマリ配信ドライバがダウンした場合に使用する、1つ以上のバックアップメール配信設定を定義できると便利です。Sometimes, an external service you have configured to send your application's mail may be down. In these cases, it can be useful to define one or more backup mail delivery configurations that will be used in case your primary delivery driver is down.

これを実現するには、アプリケーションのmail設定ファイルで、failoverトランスポートを使用するメーラーを定義する必要があります。アプリケーションのfailoverメーラー設定配列に、配送に使うメールドライバを選択する順序を規定するmailersの配列を含める必要があります。To accomplish this, you should define a mailer within your application's mail configuration file that uses the failover transport. The configuration array for your application's failover mailer should contain an array of mailers that reference the order in which mail drivers should be chosen for delivery:

'mailers' => [
    'failover' => [
        'transport' => 'failover',
        'mailers' => [
            'postmark',
            'mailgun',
            'sendmail',
        ],
    ],

    // ...
],

フェイルオーバーメーラーを定義したら、アプリケーションのmail設定ファイル内のdefault設定キーの値に、その名前を指定して、このメーラーをアプリケーションが使用するデフォルトメーラーとして設定する必要があります。Once your failover mailer has been defined, you should set this mailer as the default mailer used by your application by specifying its name as the value of the default configuration key within your application's mail configuration file:

'default' => env('MAIL_MAILER', 'failover'),

Mailableの生成Generating Mailables

Laravelアプリケーションを構築する場合、アプリケーションが送信する各タイプの電子メールは"Mailable"クラスとして表します。これらのクラスはapp/Mailディレクトリに保存されます。アプリケーションにこのディレクトリが存在しなくても心配ありません。make:mail Artisanコマンドを使用して最初のメール可能なクラスを作成するときに、生成されます。When building Laravel applications, each type of email sent by your application is represented as a "mailable" class. These classes are stored in the app/Mail directory. Don't worry if you don't see this directory in your application, since it will be generated for you when you create your first mailable class using the make:mail Artisan command:

php artisan make:mail OrderShipped

Mailableの記述Writing Mailables

Mailableクラスを生成したら、それを開いて、その内容を調べてください。まず、メール可能なクラスの設定はすべてbuildメソッドで行われることに注意してください。このメソッド内でfromsubjectviewattachなどのさまざまなメソッドを呼び出して、電子メールの表示と配信を設定できます。Once you have generated a mailable class, open it up so we can explore its contents. First, note that all of a mailable class' configuration is done in the build method. Within this method, you may call various methods such as from, subject, view, and attach to configure the email's presentation and delivery.

lightbulb">Tip!! Mailableのbuildメソッドではタイプヒントで依存を指定できます。Laravelのサービスコンテナは、これらの依存を自動的に注入します。{tip} You may type-hint dependencies on the mailable's build method. The Laravel service container[/docs/{{version}}/container] automatically injects these dependencies.

Senderの設定Configuring The Sender

fromメソッドの使用Using The from Method

まず、メールの送信者の設定について見ていきましょう。言い換えると、電子メールを送信したのは誰かです。送信者を設定するには2つの方法があります。まず、Mailableクラスのbuildメソッド内でfromメソッドを使用する方法です。First, let's explore configuring the sender of the email. Or, in other words, who the email is going to be "from". There are two ways to configure the sender. First, you may use the from method within your mailable class' build method:

/**
 * メッセージの作成
 *
 * @return $this
 */
public function build()
{
    return $this->from('example@example.com', 'Example')
                ->view('emails.orders.shipped');
}

グローバルfromアドレスの使用Using A Global from Address

ただし、アプリケーションがすべての電子メールに同じ「送信者」アドレスを使用している場合、生成する各メール可能クラスでfromメソッドを呼び出すのは面倒です。代わりに、config/mail.php設定ファイルでグローバルな「送信者」アドレスを指定できます。このアドレスは、Mailableクラス内で「送信者」アドレスを指定しない場合に使用します。However, if your application uses the same "from" address for all of its emails, it can become cumbersome to call the from method in each mailable class you generate. Instead, you may specify a global "from" address in your config/mail.php configuration file. This address will be used if no other "from" address is specified within the mailable class:

'from' => ['address' => 'example@example.com', 'name' => 'App Name'],

また、config/mail.php設定ファイル内でグローバルな"reply_to"アドレスも定義できます。In addition, you may define a global "reply_to" address within your config/mail.php configuration file:

'reply_to' => ['address' => 'example@example.com', 'name' => 'App Name'],

ビューの設定Configuring The View

Mailableクラスのbuildメソッド内で、viewメソッドを使用して、電子メールのコンテンツをレンダーするときに使用するテンプレートを指定できます。通常、各メールはBladeテンプレートを使用してコンテンツをレンダーするため、メールのHTMLを作成するときにBladeテンプレートエンジンの能力と利便性を最大限に活用できます。Within a mailable class' build method, you may use the view method to specify which template should be used when rendering the email's contents. Since each email typically uses a Blade template[/docs/{{version}}/blade] to render its contents, you have the full power and convenience of the Blade templating engine when building your email's HTML:

/**
 * メッセージの作成
 *
 * @return $this
 */
public function build()
{
    return $this->view('emails.orders.shipped');
}

lightbulb">Tip!! すべてのメールテンプレートを格納するためにresources/views/emailsディレクトリを作成することを推奨します。ただし、resources/viewsディレクトリ内ならば好きな場所へ自由に配置できます。{tip} You may wish to create a resources/views/emails directory to house all of your email templates; however, you are free to place them wherever you wish within your resources/views directory.

平文テキストの電子メールPlain Text Emails

電子メールの平文テキストバージョンを定義する場合は、textメソッドを使用します。viewメソッドと同様に、textメソッドは電子メールの内容をレンダーするために使用するテンプレート名を引数に取ります。メッセージのHTMLバージョンと平文テキストバージョンの両方を自由に定義できます。If you would like to define a plain-text version of your email, you may use the text method. Like the view method, the text method accepts a template name which will be used to render the contents of the email. You are free to define both an HTML and plain-text version of your message:

/**
 * メッセージの作成
 *
 * @return $this
 */
public function build()
{
    return $this->view('emails.orders.shipped')
                ->text('emails.orders.shipped_plain');
}

ビューデータView Data

Publicなプロパティ経由Via Public Properties

通常、電子メールのHTMLをレンダーするときに使用するデータをビューへ渡す必要があります。ビューでデータを利用できるようにする方法は2つあります。まず、Mailableクラスで定義したパブリックプロパティは、自動的にビューで使用できるようになります。したがって、たとえばMailableクラスのコンストラクタにデータを渡し、そのデータをクラスで定義したパブリックプロパティに設定できます。Typically, you will want to pass some data to your view that you can utilize when rendering the email's HTML. There are two ways you may make data available to your view. First, any public property defined on your mailable class will automatically be made available to the view. So, for example, you may pass data into your mailable class' constructor and set that data to public properties defined on the class:

<?php

namespace App\Mail;

use App\Models\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class OrderShipped extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * 注文インスタンス
     *
     * @var \App\Models\Order
     */
    public $order;

    /**
     * 新しいメッセージインスタンスの生成
     *
     * @param  \App\Models\Order  $order
     * @return void
     */
    public function __construct(Order $order)
    {
        $this->order = $order;
    }

    /**
     * メッセージを作成
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.orders.shipped');
    }
}

データをパブリックプロパティへ設定すると、ビューで自動的に利用できるようになるため、Bladeテンプレートの他のデータにアクセスするのと同じようにアクセスできます。Once the data has been set to a public property, it will automatically be available in your view, so you may access it like you would access any other data in your Blade templates:

<div>
    Price: {{ $order->price }}
</div>

withメソッド経由Via The with Method:

テンプレートへ送信する前にメールのデータの形式をカスタマイズしたい場合は、withメソッドを使用して手動でデータをビューへ渡せます。通常、Mailableクラスのコンストラクターを介してデータを渡します。ただし、このデータをprotectedまたはprivateプロパティに設定して、データがテンプレートで自動的に使用可能にならないようにする必要があります。次に、withメソッドを呼び出すときに、テンプレートで使用できるようにするデータの配列を渡します。If you would like to customize the format of your email's data before it is sent to the template, you may manually pass your data to the view via the with method. Typically, you will still pass data via the mailable class' constructor; however, you should set this data to protected or private properties so the data is not automatically made available to the template. Then, when calling the with method, pass an array of data that you wish to make available to the template:

<?php

namespace App\Mail;

use App\Models\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class OrderShipped extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * 注文インスタンス
     *
     * @var \App\Models\Order
     */
    protected $order;

    /**
     * 新しいメッセージインスタンスの生成
     *
     * @param  \App\Models\Order  $order
     * @return void
     */
    public function __construct(Order $order)
    {
        $this->order = $order;
    }

    /**
     * メッセージを作成
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.orders.shipped')
                    ->with([
                        'orderName' => $this->order->name,
                        'orderPrice' => $this->order->price,
                    ]);
    }
}

データがwithメソッドに渡されると、ビューで自動的に利用できるようになるため、Bladeテンプレートの他のデータにアクセスするのと同じようにアクセスできます。Once the data has been passed to the with method, it will automatically be available in your view, so you may access it like you would access any other data in your Blade templates:

<div>
    Price: {{ $orderPrice }}
</div>

添付Attachments

電子メールに添付ファイルを追加するには、Mailableクラスのbuildメソッド内でattachメソッドを使用します。attachメソッドは、ファイルへのフルパスを最初の引数に受けます。To add attachments to an email, use the attach method within the mailable class' build method. The attach method accepts the full path to the file as its first argument:

/**
 * メッセージを作成
 *
 * @return $this
 */
public function build()
{
    return $this->view('emails.orders.shipped')
                ->attach('/path/to/file');
}

メッセージにファイルを添付する場合、arrayattachメソッドの2番目の引数に渡すことにより、表示名やMIMEタイプを指定することもできます。When attaching files to a message, you may also specify the display name and / or MIME type by passing an array as the second argument to the attach method:

/**
 * メッセージを作成
 *
 * @return $this
 */
public function build()
{
    return $this->view('emails.orders.shipped')
                ->attach('/path/to/file', [
                    'as' => 'name.pdf',
                    'mime' => 'application/pdf',
                ]);
}

ディスクからファイルを添付Attaching Files From Disk

ファイルシステムディスクのいずれかにファイルを保存している場合は、attachFromStorageメソッドを使用してファイルを電子メールに添付できます。If you have stored a file on one of your filesystem disks[/docs/{{version}}/filesystem], you may attach it to the email using the attachFromStorage method:

/**
 * メッセージを作成
 *
 * @return $this
 */
public function build()
{
   return $this->view('emails.orders.shipped')
               ->attachFromStorage('/path/to/file');
}

必要に応じて、attachFromStorageメソッドの2番目と3番目の引数を使用して、ファイルの添付ファイル名と追加オプションを指定できます。If necessary, you may specify the file's attachment name and additional options using the second and third arguments to the attachFromStorage method:

/**
 * メッセージを作成
 *
 * @return $this
 */
public function build()
{
   return $this->view('emails.orders.shipped')
               ->attachFromStorage('/path/to/file', 'name.pdf', [
                   'mime' => 'application/pdf'
               ]);
}

デフォルトのディスク以外のストレージディスクを指定する必要がある場合は、attachFromStorageDiskメソッドを使用します。The attachFromStorageDisk method may be used if you need to specify a storage disk other than your default disk:

/**
 * メッセージを作成
 *
 * @return $this
 */
public function build()
{
   return $this->view('emails.orders.shipped')
               ->attachFromStorageDisk('s3', '/path/to/file');
}

素のデータの添付ファイルRaw Data Attachments

attachDataメソッドを使用して、素のバイト文字列を添付ファイルとして添付できます。たとえば、メモリ内にPDFを生成し、ディスクに書き込まずに電子メールに添付する場合は、この方法を使用できます。attachDataメソッドは、最初の引数に素のデータバイトを取り、2番目の引数にファイルの名前、3番目の引数にオプションの配列を取ります。The attachData method may be used to attach a raw string of bytes as an attachment. For example, you might use this method if you have generated a PDF in memory and want to attach it to the email without writing it to disk. The attachData method accepts the raw data bytes as its first argument, the name of the file as its second argument, and an array of options as its third argument:

/**
 * メッセージを作成
 *
 * @return $this
 */
public function build()
{
    return $this->view('emails.orders.shipped')
                ->attachData($this->pdf, 'name.pdf', [
                    'mime' => 'application/pdf',
                ]);
}

インライン添付Inline Attachments

インライン画像をメールに埋め込むのは、通常面倒です。ただし、Laravelはメールに画像を添付する便利な方法を提供しています。インライン画像を埋め込むには、メールテンプレート内の$message変数でembedメソッドを使用します。Laravelは自動的に$message変数をすべてのメールテンプレートで利用できるようにするので、手動で渡すことを心配する必要はありません。Embedding inline images into your emails is typically cumbersome; however, Laravel provides a convenient way to attach images to your emails. To embed an inline image, use the embed method on the $message variable within your email template. Laravel automatically makes the $message variable available to all of your email templates, so you don't need to worry about passing it in manually:

<body>
    Here is an image:

    <img src="{{ $message->embed($pathToImage) }}">
</body>

Note: note 平文ンテキストメッセージはインライン添付ファイルを利用しないため、$message変数は平文テキストメッセージテンプレートでは使用できません。{note} The $message variable is not available in plain-text message templates since plain-text messages do not utilize inline attachments.

素のデータの添付ファイルへの埋め込みEmbedding Raw Data Attachments

電子メールテンプレートに埋め込みたい素の画像データ文字列がすでにある場合は、$message変数でembedDataメソッドを呼び出すことができます。embedDataメソッドを呼び出すときは、埋め込み画像に割り当てる必要のあるファイル名を指定する必要があります。If you already have a raw image data string you wish to embed into an email template, you may call the embedData method on the $message variable. When calling the embedData method, you will need to provide a filename that should be assigned to the embedded image:

<body>
    Here is an image from raw data:

    <img src="{{ $message->embedData($data, 'example-image.jpg') }}">
</body>

SwiftMailerメッセージのカスタマイズCustomizing The SwiftMailer Message

Mailable基本クラスのwithSwiftMessageメソッドを使用すると、メッセージを送信する前にSwiftMailerメッセージインスタンスで呼び出されるクロージャを登録できます。これにより、メッセージが配信される前に、メッセージを大幅にカスタマイズする機会が得られます。The withSwiftMessage method of the Mailable base class allows you to register a closure which will be invoked with the SwiftMailer message instance before sending the message. This gives you an opportunity to deeply customize the message before it is delivered:

/**
 * メッセージを作成
 *
 * @return $this
 */
public function build()
{
    $this->view('emails.orders.shipped');

    $this->withSwiftMessage(function ($message) {
        $message->getHeaders()->addTextHeader(
            'Custom-Header', 'Header Value'
        );
    });

    return $this;
}

Markdown MailableMarkdown Mailables

Markdown Mailableメッセージを使用すると、Mailableでメール通知の事前に作成されたテンプレートとコンポーネントを利用できます。メッセージはMarkdownで記述されているため、Laravelはメッセージの美しくレスポンシブなHTMLテンプレートをレンダーすると同時に、平文テキスト版も自動的に生成できます。Markdown mailable messages allow you to take advantage of the pre-built templates and components of mail notifications[/docs/{{version}}/notifications#mail-notifications] in your mailables. Since the messages are written in Markdown, Laravel is able to render beautiful, responsive HTML templates for the messages while also automatically generating a plain-text counterpart.

Markdown Mailableの生成Generating Markdown Mailables

対応するMarkdownテンプレートを使用してMailableファイルを生成するには、make:mail Artisanコマンドの--markdownオプションを使用します。To generate a mailable with a corresponding Markdown template, you may use the --markdown option of the make:mail Artisan command:

php artisan make:mail OrderShipped --markdown=emails.orders.shipped

次に、Mailableオブジェクトをそのbuildメソッド内で設定するときに、viewメソッドの代わりにmarkdownメソッドを呼び出します。markdownメソッドは、Markdownテンプレートの名前と、テンプレートで使用するデータ配列をオプションとして引数に取ります。Then, when configuring the mailable within its build method, call the markdown method instead of the view method. The markdown method accepts the name of the Markdown template and an optional array of data to make available to the template:

/**
 * メッセージを作成
 *
 * @return $this
 */
public function build()
{
    return $this->from('example@example.com')
                ->markdown('emails.orders.shipped', [
                    'url' => $this->orderUrl,
                ]);
}

Markdownメッセージの記述Writing Markdown Messages

Markdown Mailableは、BladeコンポーネントとMarkdown構文の組み合わせを使用して、Laravelに組み込まれた電子メールUIコンポーネントを活用しながら、メールメッセージを簡単に作成できるようにします。Markdown mailables use a combination of Blade components and Markdown syntax which allow you to easily construct mail messages while leveraging Laravel's pre-built email UI components:

@component('mail::message')
# Order Shipped

Your order has been shipped!

@component('mail::button', ['url' => $url])
View Order
@endcomponent

Thanks,<br>
{{ config('app.name') }}
@endcomponent

lightbulb">Tip!! Markdownメールを書くときに余分なインデントを使用しないでください。Markdown標準に従って、Markdownパーサーはインデントされたコンテンツをコードブロックとしてレンダリングします。{tip} Do not use excess indentation when writing Markdown emails. Per Markdown standards, Markdown parsers will render indented content as code blocks.

ボタンコンポーネントButton Component

ボタンコンポーネントは、中央に配置されたボタンリンクをレンダーします。コンポーネントは、urlとオプションのcolorの2つの引数を取ります。サポートしている色は、primarysuccesserrorです。メッセージには、必要なだけのボタンコンポーネントを追加できます。The button component renders a centered button link. The component accepts two arguments, a url and an optional color. Supported colors are primary, success, and error. You may add as many button components to a message as you wish:

@component('mail::button', ['url' => $url, 'color' => 'success'])
View Order
@endcomponent

パネルコンポーネントPanel Component

パネルコンポーネントは、メッセージの残りの部分とはわずかに異なる背景色を持つパネルで、指定するテキストのブロックをレンダーします。これにより、特定のテキストブロックに注意を引くことができます。The panel component renders the given block of text in a panel that has a slightly different background color than the rest of the message. This allows you to draw attention to a given block of text:

@component('mail::panel')
This is the panel content.
@endcomponent

テーブルコンポーネントTable Component

テーブルコンポーネントを使用すると、MarkdownテーブルをHTMLテーブルに変換できます。コンポーネントは、そのコンテンツとしてMarkdownテーブルを受け入れます。テーブルの列の配置は、デフォルトのMarkdownテーブルの配置構文をサポートします。The table component allows you to transform a Markdown table into an HTML table. The component accepts the Markdown table as its content. Table column alignment is supported using the default Markdown table alignment syntax:

@component('mail::table')
| Laravel       | Table         | Example  |
| ------------- |:-------------:| --------:|
| Col 2 is      | Centered      | $10      |
| Col 3 is      | Right-Aligned | $20      |
@endcomponent

コンポーネントのカスタマイズCustomizing The Components

カスタマイズするために、すべてのMarkdownメールコンポーネントを自身のアプリケーションへエクスポートできます。コンポーネントをエクスポートするには、vendor:publish Artisanコマンドを使用してlaravel-mailアセットタグでリソース公開します。You may export all of the Markdown mail components to your own application for customization. To export the components, use the vendor:publish Artisan command to publish the laravel-mail asset tag:

php artisan vendor:publish --tag=laravel-mail

このコマンドは、Markdownメールコンポーネントをresources/views/vendor/mailディレクトリへリソース公開します。mailディレクトリにはhtmlディレクトリとtextディレクトリが含まれ、それぞれに利用可能なすべてのコンポーネントのそれぞれの表現が含まれます。これらのコンポーネントは自由にカスタマイズできます。This command will publish the Markdown mail components to the resources/views/vendor/mail directory. The mail directory will contain an html and a text directory, each containing their respective representations of every available component. You are free to customize these components however you like.

CSSのカスタマイズCustomizing The CSS

コンポーネントをエクスポートした後、resources/views/vendor/mail/html/themesディレクトリにはdefault.cssファイルが含まれます。このファイルのCSSをカスタマイズすると、MarkdownメールメッセージのHTML表現内でスタイルが自動的にインラインCSSスタイルに変換されます。After exporting the components, the resources/views/vendor/mail/html/themes directory will contain a default.css file. You may customize the CSS in this file and your styles will automatically be converted to inline CSS styles within the HTML representations of your Markdown mail messages.

LaravelのMarkdownコンポーネント用にまったく新しいテーマを作成したい場合は、CSSファイルをhtml/themesディレクトリに配置できます。CSSファイルに名前を付けて保存した後、アプリケーションのconfig/mail.php設定ファイルのthemeオプションを更新して、新しいテーマの名前と一致させます。If you would like to build an entirely new theme for Laravel's Markdown components, you may place a CSS file within the html/themes directory. After naming and saving your CSS file, update the theme option of your application's config/mail.php configuration file to match the name of your new theme.

個々のMailableのテーマをカスタマイズするには、Mailableクラスの$themeプロパティを、そのMailableを送信するときに使用するテーマの名前に設定します。To customize the theme for an individual mailable, you may set the $theme property of the mailable class to the name of the theme that should be used when sending that mailable.

メール送信Sending Mail

メッセージを送信するには、Mailファサードtoメソッドを使用します。toメソッドは、電子メールアドレス、ユーザーインスタンス、またはユーザーのコレクションを受け入れます。オブジェクトまたはオブジェクトのコレクションを渡すと、メーラーは電子メールの受信者を決定するときに自動的にemailおよびnameプロパティを使用するため、これらの属性がオブジェクトで使用可能であることを確認してください。受信者を指定したら、Mailableクラスのインスタンスをsendメソッドに渡すことができます。To send a message, use the to method on the Mail facade[/docs/{{version}}/facades]. The to method accepts an email address, a user instance, or a collection of users. If you pass an object or collection of objects, the mailer will automatically use their email and name properties when determining the email's recipients, so make sure these attributes are available on your objects. Once you have specified your recipients, you may pass an instance of your mailable class to the send method:

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Mail\OrderShipped;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;

class OrderShipmentController extends Controller
{
    /**
     * 指定注文を発送
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $order = Order::findOrFail($request->order_id);

        // 注文を発送…

        Mail::to($request->user())->send(new OrderShipped($order));
    }
}

メッセージを送信するときに「宛先」の受信者を指定するだけに限定されません。それぞれのメソッドをチェーン化することで、「to」、「cc」、「bcc」の受信者を自由に設定できます。You are not limited to just specifying the "to" recipients when sending a message. You are free to set "to", "cc", and "bcc" recipients by chaining their respective methods together:

Mail::to($request->user())
    ->cc($moreUsers)
    ->bcc($evenMoreUsers)
    ->send(new OrderShipped($order));

受信者をループするLooping Over Recipients

場合によっては、受信者/電子メールアドレスの配列を反復処理して、受信者のリストにMailableファイルを送信する必要が起きるでしょう。しかし、toメソッドはメールアドレスをMailable受信者のリストに追加するため、ループを繰り返すたびに、以前のすべての受信者に別のメールが送信されます。したがって、受信者ごとにMailableインスタンスを常に再作成する必要があります。Occasionally, you may need to send a mailable to a list of recipients by iterating over an array of recipients / email addresses. However, since the to method appends email addresses to the mailable's list of recipients, each iteration through the loop will send another email to every previous recipient. Therefore, you should always re-create the mailable instance for each recipient:

foreach (['taylor@example.com', 'dries@example.com'] as $recipient) {
    Mail::to($recipient)->send(new OrderShipped($order));
}

特定のメーラーを介してメールを送信Sending Mail Via A Specific Mailer

デフォルトでは、Laravelはアプリケーションのmail設定ファイルでdefaultメーラーとして設定されたメーラーを使用してメールを送信します。しかし、mailerメソッドを使用して、特定のメーラー設定を使用してメッセージを送信することができます。By default, Laravel will send email using the mailer configured as the default mailer in your application's mail configuration file. However, you may use the mailer method to send a message using a specific mailer configuration:

Mail::mailer('postmark')
        ->to($request->user())
        ->send(new OrderShipped($order));

メールのキュー投入Queueing Mail

メールメッセージのキュー投入Queueing A Mail Message

電子メールメッセージの送信はアプリケーションのレスポンス時間に悪影響を与える可能性があるため、多くの開発者はバックグラウンド送信のために電子メールメッセージをキューに投入することを選択します。Laravelは組み込みの統一キューAPIを使用してこれを簡単にしています。メールメッセージをキューに投入するには、メッセージの受信者を指定した後、Mailファサードでqueueメソッドを使用します。Since sending email messages can negatively impact the response time of your application, many developers choose to queue email messages for background sending. Laravel makes this easy using its built-in unified queue API[/docs/{{version}}/queues]. To queue a mail message, use the queue method on the Mail facade after specifying the message's recipients:

Mail::to($request->user())
    ->cc($moreUsers)
    ->bcc($evenMoreUsers)
    ->queue(new OrderShipped($order));

このメソッドは、メッセージがバックグラウンドで送信されるように、ジョブをキューへ自動的に投入処理します。この機能を使用する前に、キューを設定しておく必要があります。This method will automatically take care of pushing a job onto the queue so the message is sent in the background. You will need to configure your queues[/docs/{{version}}/queues] before using this feature.

遅延メッセージキューDelayed Message Queueing

キューに投入した電子メールメッセージの配信を遅らせたい場合は、laterメソッドを使用します。laterメソッドは最初の引数にメッセージの送信時期を示すDateTimeインスタンスを取ります。。If you wish to delay the delivery of a queued email message, you may use the later method. As its first argument, the later method accepts a DateTime instance indicating when the message should be sent:

Mail::to($request->user())
    ->cc($moreUsers)
    ->bcc($evenMoreUsers)
    ->later(now()->addMinutes(10), new OrderShipped($order));

特定のキューへの投入Pushing To Specific Queues

make:mailコマンドを使用して生成したすべてのMailableクラスはIlluminate\Bus\Queueableトレイトを利用するため、任意のMailableクラスインスタンスでonQueueメソッドとonConnectionメソッドを呼び出して、メッセージに使う接続とキュー名を指定できます。Since all mailable classes generated using the make:mail command make use of the Illuminate\Bus\Queueable trait, you may call the onQueue and onConnection methods on any mailable class instance, allowing you to specify the connection and queue name for the message:

$message = (new OrderShipped($order))
                ->onConnection('sqs')
                ->onQueue('emails');

Mail::to($request->user())
    ->cc($moreUsers)
    ->bcc($evenMoreUsers)
    ->queue($message);

デフォルトでのキュー投入Queueing By Default

常にキューに入れたいMailableクラスがある場合は、クラスにShouldQueue契約を実装できます。これで、メール送信時にsendメソッドを呼び出しても、この契約を実装しているため、Mailableはキューへ投入されます。If you have mailable classes that you want to always be queued, you may implement the ShouldQueue contract on the class. Now, even if you call the send method when mailing, the mailable will still be queued since it implements the contract:

use Illuminate\Contracts\Queue\ShouldQueue;

class OrderShipped extends Mailable implements ShouldQueue
{
    //
}

Mailableのキュー投入とデータベーストランザクションQueued Mailables & Database Transactions

キュー投入されたMailableがデータベーストランザクション内でディスパッチされると、データベーストランザクションがコミットされる前にキューによって処理される場合があります。これが発生した場合、データベーストランザクション中にモデルまたはデータベースレコードに加えた更新は、データベースにまだ反映されていない可能性があります。さらに、トランザクション内で作成したモデルまたはデータベースレコードは、データベースに存在しない可能性があります。Mailableがこれらのモデルに依存している場合、キューに入れられたMailableを送信するジョブが処理されるときに予期しないエラーが発生する可能性があります。When queued mailables are dispatched within database transactions, they may be processed by the queue before the database transaction has committed. When this happens, any updates you have made to models or database records during the database transaction may not yet be reflected in the database. In addition, any models or database records created within the transaction may not exist in the database. If your mailable depends on these models, unexpected errors can occur when the job that sends the queued mailable is processed.

キュー接続のafter_commit設定オプションがfalseに設定されている場合でも、メールメッセージ送信時にafterCommitメソッドを呼び出せば、キュー投入する特定のMailableが、オープンしているすべてのデータベーストランザクションのコミット後に、ディスパッチすると示せます。If your queue connection's after_commit configuration option is set to false, you may still indicate that a particular queued mailable should be dispatched after all open database transactions have been committed by calling the afterCommit method when sending the mail message:

Mail::to($request->user())->send(
    (new OrderShipped($order))->afterCommit()
);

あるいは、Mailableのコンストラクタで、afterCommitメソッドを呼び出すこともできます。Alternatively, you may call the afterCommit method from your mailable's constructor:

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class OrderShipped extends Mailable implements ShouldQueue
{
    use Queueable, SerializesModels;

    /**
     * 新しいメッセージインスタンスの生成
     *
     * @return void
     */
    public function __construct()
    {
        $this->afterCommit();
    }
}

lightbulb">Tip!! これらの問題の回避方法の詳細は、キュー投入したジョブとデータベーストランザクションに関するドキュメントを確認してください。{tip} To learn more about working around these issues, please review the documentation regarding queued jobs and database transactions[/docs/{{version}}/queues#jobs-and-database-transactions].

MailableのレンダーRendering Mailables

MailableのHTMLコンテンツを送信せずにキャプチャしたい場合があります。これを行うには、Mailableのrenderメソッドを呼び出してください。このメソッドは、Mailableファイルの評価済みHTMLコンテンツを文字列として返します。Sometimes you may wish to capture the HTML content of a mailable without sending it. To accomplish this, you may call the render method of the mailable. This method will return the evaluated HTML content of the mailable as a string:

use App\Mail\InvoicePaid;
use App\Models\Invoice;

$invoice = Invoice::find(1);

return (new InvoicePaid($invoice))->render();

ブラウザによるMailableのプレビューPreviewing Mailables In The Browser

Mailableのテンプレートを設計するときは、通常のBladeテンプレートのように、レンダー済みMailableをブラウザですばやくプレビューできると便利です。このためLaravelでは、ルートクロージャまたはコントローラから直接Mailableを返せます。Mailableが返されると、ブラウザでレンダーされ表示されるため、実際の電子メールアドレスへ送信しなくても、デザインをすばやくプレビューできます。When designing a mailable's template, it is convenient to quickly preview the rendered mailable in your browser like a typical Blade template. For this reason, Laravel allows you to return any mailable directly from a route closure or controller. When a mailable is returned, it will be rendered and displayed in the browser, allowing you to quickly preview its design without needing to send it to an actual email address:

Route::get('/mailable', function () {
    $invoice = App\Models\Invoice::find(1);

    return new App\Mail\InvoicePaid($invoice);
});

Note: note インライン添付ファイルは、Mailableファイルがブラウザでプレビューされたときにレンダリングされません。これらのメーラブルをプレビューするには、MailHogHELOなどのメールテストアプリケーションに送信する必要があります。{note} Inline attachments[#inline-attachments] will not be rendered when a mailable is previewed in your browser. To preview these mailables, you should send them to an email testing application such as MailHog[https://github.com/mailhog/MailHog] or HELO[https://usehelo.com].

Mailableの多言語化Localizing Mailables

Laravelを使用すると、リクエストの現在のロケール以外のロケールでMailableファイルを送信でき、メールがキュー投入される場合でもこのロケールを記憶しています。Laravel allows you to send mailables in a locale other than the request's current locale, and will even remember this locale if the mail is queued.

これを実現するために、Mailファサードは目的の言語を設定するためのlocaleメソッドを提供します。Mailableのテンプレートが評価されると、アプリケーションはこのロケールに変更され、評価が完了すると前のロケールに戻ります。To accomplish this, the Mail facade offers a locale method to set the desired language. The application will change into this locale when the mailable's template is being evaluated and then revert back to the previous locale when evaluation is complete:

Mail::to($request->user())->locale('es')->send(
    new OrderShipped($order)
);

ユーザー優先ロケールUser Preferred Locales

場合によっては、アプリケーションは各ユーザーの優先ロケールを保存しています。1つ以上のモデルにHasLocalePreferenceコントラクトを実装することで、メールを送信するときにこの保存されたロケールを使用するようにLaravelに指示できます。Sometimes, applications store each user's preferred locale. By implementing the HasLocalePreference contract on one or more of your models, you may instruct Laravel to use this stored locale when sending mail:

use Illuminate\Contracts\Translation\HasLocalePreference;

class User extends Model implements HasLocalePreference
{
    /**
     * ユーザーの希望するロケールを取得
     *
     * @return string
     */
    public function preferredLocale()
    {
        return $this->locale;
    }
}

このインターフェイスを実装すると、LaravelはMailableと通知をモデルへ送信するとき、自動的に優先ロケールを使用します。したがって、このインターフェイスを使用する場合、localeメソッドを呼び出す必要はありません。Once you have implemented the interface, Laravel will automatically use the preferred locale when sending mailables and notifications to the model. Therefore, there is no need to call the locale method when using this interface:

Mail::to($request->user())->send(new OrderShipped($order));

MailableのテストTesting Mailables

Laravelは、Mailableに期待するコンテンツが含まれていることをテストするための便利な方法をいくつか提供しています。これらのメソッドは、assertSeeInHtmlassertDontSeeInHtmlassertSeeInTextassertDontSeeInTextです。Laravel provides several convenient methods for testing that your mailables contain the content that you expect. These methods are: assertSeeInHtml, assertDontSeeInHtml, assertSeeInText, and assertDontSeeInText.

ご想像のとおり、"HTML"アサートは、メーラブルのHTMLバージョンに特定の文字列が含まれていることを宣言し、"text"アサートは、Mailableの平文テキストバージョンに特定の文字列が含まれていることを宣言します。As you might expect, the "HTML" assertions assert that the HTML version of your mailable contains a given string, while the "text" assertions assert that the plain-text version of your mailable contains a given string:

use App\Mail\InvoicePaid;
use App\Models\User;

public function test_mailable_content()
{
    $user = User::factory()->create();

    $mailable = new InvoicePaid($user);

    $mailable->assertSeeInHtml($user->email);
    $mailable->assertSeeInHtml('Invoice Paid');

    $mailable->assertSeeInText($user->email);
    $mailable->assertSeeInText('Invoice Paid');
}

Mailableの送信テストTesting Mailable Sending

指定のMailableが特定のユーザーへ「送信」されたことをアサートするテストとは別に、Mailableのコンテンツをテストするのを推奨します。メールが送信されたことをテストする方法については、Mail fakeのドキュメントをご覧ください。We suggest testing the content of your mailables separately from your tests that assert that a given mailable was "sent" to a specific user. To learn how to test that mailables were sent, check out our documentation on the Mail fake[/docs/{{version}}/mocking#mail-fake].

メールとローカル開発Mail & Local Development

電子メールを送信するアプリケーションを開発する場合、実際の電子メールアドレスに電子メールを送信したくない場合があります。Laravelは、ローカル開発中に実際の電子メールの送信を「無効にする」ためのいくつかの方法を提供します。When developing an application that sends email, you probably don't want to actually send emails to live email addresses. Laravel provides several ways to "disable" the actual sending of emails during local development.

LogドライバLog Driver

メールを送信する代わりに、logメールドライバは検査のためにすべてのメールメッセージをログファイルに書き込みます。通常、このドライバはローカル開発中にのみ使用されます。環境ごとのアプリケーションの設定の詳細については、設定ドキュメントを確認してください。Instead of sending your emails, the log mail driver will write all email messages to your log files for inspection. Typically, this driver would only be used during local development. For more information on configuring your application per environment, check out the configuration documentation[/docs/{{version}}/configuration#environment-configuration].

HELO/Mailtrap/MailHogHELO / Mailtrap / MailHog

もしくは、HELOMailtrapなどのサービスとsmtpドライバを使用して、メールメッセージを「ダミー」メールボックスに送信可能です。本当の電子メールクライアントでそれらを表示できます。このアプローチには、Mailtrapのメッセージビューアで最終的な電子メールを実際に調べられるという利点があります。Alternatively, you may use a service like HELO[https://usehelo.com] or Mailtrap[https://mailtrap.io] and the smtp driver to send your email messages to a "dummy" mailbox where you may view them in a true email client. This approach has the benefit of allowing you to actually inspect the final emails in Mailtrap's message viewer.

Laravel Sailを使用している場合は、MailHogを使用してメッセージをプレビューできます。Sailの実行中は、http://localhost:8025でMailHogインターフェイスにアクセスできます。If you are using Laravel Sail[/docs/{{version}}/sail], you may preview your messages using MailHog[https://github.com/mailhog/MailHog]. When Sail is running, you may access the MailHog interface at: http://localhost:8025.

グローバルなtoアドレスの使用Using A Global to Address

最後に、Mailファサードが提供するalwaysToメソッドを呼び出し、グローバルな「宛先」アドレスを指定する方法です。通常、このメソッドは、アプリケーションのサービスプロバイダのbootメソッドから呼び出すべきでしょう。Finally, you may specify a global "to" address by invoking the alwaysTo method offered by the Mail facade. Typically, this method should be called from the boot method of one of your application's service providers:

use Illuminate\Support\Facades\Mail;

/**
 * アプリケーションの全サービスの初期起動処理
 *
 * @return void
 */
public function boot()
{
    if ($this->app->environment('local')) {
        Mail::alwaysTo('taylor@example.com');
    }
}

イベントEvents

Laravelは、メールメッセージの送信プロセス中に2つのイベントを発行します。MessageSendingイベントはメッセージが送信される前に発生し、MessageSentイベントはメッセージが送信された後に発生します。これらのイベントは、メールをキューへ投入したときではなく、メールが送信されているときに発生することを忘れないでください。このイベントのイベントリスナは、App\Providers\EventServiceProviderサービスプロバイダで登録できます。Laravel fires two events during the process of sending mail messages. The MessageSending event is fired prior to a message being sent, while the MessageSent event is fired after a message has been sent. Remember, these events are fired when the mail is being sent, not when it is queued. You may register event listeners for this event in your App\Providers\EventServiceProvider service provider:

/**
 * アプリケーションのイベントリスナマッピング
 *
 * @var array
 */
protected $listen = [
    'Illuminate\Mail\Events\MessageSending' => [
        'App\Listeners\LogSendingMessage',
    ],
    'Illuminate\Mail\Events\MessageSent' => [
        'App\Listeners\LogSentMessage',
    ],
];

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作