Readouble

Laravel 5.7 メール

イントロダクションIntroduction

Laravelは人気の高いSwiftMailerライブラリーのクリーンでシンプルなAPIを提供しています。SMTP、Mailgun、SparkPost、Amazon SES、sendmailドライバーを提供しており、選択したローカルやクラウドベースのサービスを使い、素早くメール送信が開始できるようにしています。Laravel provides a clean, simple API over the popular SwiftMailer[https://swiftmailer.symfony.com/] library with drivers for SMTP, Mailgun, SparkPost, Amazon SES, and sendmail, allowing you to quickly get started sending mail through a local or cloud based service of your choice.

ドライバの動作要件Driver Prerequisites

MailgunとSparkPostなどAPIベースドライバはシンプルでSMTPサーバよりも高速です。可能であれば、こうしたドライバを使用しましょう。APIドライバはすべて、Guzzle HTTPライブラリを必要としますので、Composerパッケージマネージャでインストールしてください。The API based drivers such as Mailgun and SparkPost are often simpler and faster than SMTP servers. If possible, you should use one of these drivers. All of the API drivers require the Guzzle HTTP library, which may be installed via the Composer package manager:

composer require guzzlehttp/guzzle

MailgunドライバMailgun Driver

Mailgunドライバを使用する場合、最初にGuzzleをインストールしてください。それからconfig/mail.php設定ファイル中のdriverオプションをmailgunに設定してください。次にconfig/services.php設定ファイルが以下のオプションを含んでいるか確認してください。To use the Mailgun driver, first install Guzzle, then set the driver 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' => 'your-mailgun-domain',
    'secret' => 'your-mailgun-key',
],

"US" Mailgunリージョンを使用しない場合は、services設定ファイルで、リージョンのエンドポイントを定義してください。If you are not using the "US" 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' => 'your-mailgun-domain',
    'secret' => 'your-mailgun-key',
    'endpoint' => 'api.eu.mailgun.net',
],

SparkPostドライバSparkPost Driver

SparkPostドライバを使用するには、最初にGuzzleをインストールし、次にconfig/mail.php設定ファイル中のdriverオプションをsparkpostに設定してください。config/services.php設定ファイルに以下のオプションが含まれているか確認してください。To use the SparkPost driver, first install Guzzle, then set the driver option in your config/mail.php configuration file to sparkpost. Next, verify that your config/services.php configuration file contains the following options:

'sparkpost' => [
    'secret' => 'your-sparkpost-key',
],

必要であれば、利用されるべきAPIエンドポイントを設定することもできます。If necessary, you may also configure which API endpoint[https://developers.sparkpost.com/api/#header-endpoints] should be used:

'sparkpost' => [
    'secret' => 'your-sparkpost-key',
    'options' => [
        'endpoint' => 'https://api.eu.sparkpost.com/api/v1/transmissions',
    ],
],

SESドライバSES Driver

Amazon SESドライバを使う場合、Amazon AWS SDK for PHPをインストールしてください。composer.jsonファイルのrequireセクションに以下の行を追加し、composer updateコマンドを実行します。To use the Amazon SES driver you must first install the Amazon AWS SDK for PHP. You may install this library by adding the following line to your composer.json file's require section and running the composer update command:

"aws/aws-sdk-php": "~3.0"

次にconfig/mail.php設定ファイルのdriverオプションをsesに設定します。それからconfig/services.php設定ファイルが以下の内容になっているか確認してください。Next, set the driver 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' => 'your-ses-key',
    'secret' => 'your-ses-secret',
    'region' => 'ses-region',  // e.g. us-east-1
],

SESのSendRawEmailリクエストを実行する時に、追加オプションを含めたい場合は、ses設定の中にoptions配列を定義してください。If you need to include additional options[https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-email-2010-12-01.html#sendrawemail] when executing the SES SendRawEmail request, you may define an options array within your ses configuration:

'ses' => [
    'key' => 'your-ses-key',
    'secret' => 'your-ses-secret',
    'region' => 'ses-region',  // e.g. us-east-1
    'options' => [
        'ConfigurationSetName' => 'MyConfigurationSet',
        'Tags' => [
            [
                'Name' => 'foo',
                'Value' => 'bar',
            ],
        ],
    ],
],

Mailable概論Generating Mailables

Laravelではアプリケーションが送信する、各種メールタイプを"mailable"クラスとして表します。これらのクラスは、app/Mailディレクトリに保存します。アプリケーションにこのディレクトリが存在していなくても、心配ありません。make:mailコマンドを使用して、最初にmailableクラスを生成する時に、作成されます。In Laravel, 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 command:

php artisan make:mail OrderShipped

MailableプログラミングWriting Mailables

全mailableクラスの設定は、buildメソッド中で行います。このメソッド中でメールのプレゼンテーションとデリバリーを設定する、fromsubjectviewattachなど様々なメソッドを呼び出します。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.

Senderの設定Configuring The Sender

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

最初に、メールの送信者の設定を見てみましょう。言い換えれば、"from"により、メールを送信する人を指定します。送信者の設定には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')
                ->view('emails.orders.shipped');
}

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

もし、アプリケーションで同じ"from"アドレスを全メールで使用するのであれば、生成する全mailableクラスでfromメソッドを呼び出すのは面倒です。代わりに、グローバルな"from"アドレスをconfig/mail.php設定ファイルで指定しましょう。このアドレスは、mailableクラスの中で、"from"アドレスが指定されなかった場合に使用されます。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 a 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クラスで定義したpublicプロパティは、ビューで自動的に利用できます。そのため、たとえば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\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class OrderShipped extends Mailable
{
    use Queueable, SerializesModels;

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

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

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

データをpublicプロパティにセットしたら、自動的にビューで使用できるようになり、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クラスのコンストラクタで渡すことになるでしょう。しかし、自動的にテンプレートで使用可能にならないように、protectedprivateプロパティへデータをセットしてください。それから、テンプレートで使用したいデータの配列を引数として、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\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class OrderShipped extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * 注文インスタンス
     *
     * @var Order
     */
    protected $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

メールへ添付するには、attachメソッドをmailableクラスのbuildメソッド中で呼び出します。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');
}

ファイルをメッセージ添付する場合、attachメソッドの第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('email.orders.shipped')
               ->attachFromStorage('/path/to/file');
}

必要に応じ、ファイルの添付名と追加のオプションを第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('email.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('email.orders.shipped')
               ->attachFromStorageDisk('s3', '/path/to/file');
}

Rawデータ添付Raw Data Attachments

attachDataメソッドは添付内容のバイト文字列をそのまま添付する場合に使用します。たとえば、メモリ中でPDFを生成し、それをディスクに書き出さずに、メールへ添付したい場合にこのメソッドを使用できます。attachDataメソッドはrawデータバイトを最初の引数に取り、ファイル名を第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は画像をメールに付け、最適なCIDを得る便利な方法を提供しています。インラインイメージを埋め込むには、メールビューの中で$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 and retrieving the appropriate CID. 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>
    ここに画像:

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

Note: note Markdownメッセージでは、$message変数は使用できません。{note} $message variable is not available in markdown messages.

添付Rawデータの埋め込みEmbedding Raw Data Attachments

メールテンプレートへ埋め込むrawデータ文字列を既に用意してある場合は、$message変数のembedDataメソッドを使ってください。If you already have a raw data string you wish to embed into an email template, you may use the embedData method on the $message variable:

<body>
    ここにrawデータからの画像:

    <img src="{{ $message->embedData($data, $name) }}">
</body>

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

MailableベースクラスのwithSwiftMessageクラスにより、メッセージ送信前にSwiftMailerメッセージインスタンスを直接呼び出すコールバクを登録できます。これにより配信する前に、メッセージを送信する機会を得られます。The withSwiftMessage method of the Mailable base class allows you to register a callback which will be invoked with the raw SwiftMailer message instance before sending the message. This gives you an opportunity to 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', 'HeaderValue');
    });
}

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

次に、buildメソッド内で、Mailableを設定します。viewメソッドの代わりに、markdownメソッドを呼び出します。markdownメソッドはMarkdownテンプレートの名前とテンプレートで使用するデータの配列を引数に取ります。Then, when configuring the mailable within its build method, call the markdown method instead of the view method. The markdown methods 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');
}

Markdown Messageの記述Writing Markdown Messages

Markdown MailableではBladeコンポーネントとMarkdown記法が利用でき、メールメッセージを簡単に構築できると同時に、Laravelが用意しているコンポーネントも活用できます。Markdown mailables use a combination of Blade components and Markdown syntax which allow you to easily construct mail messages while leveraging Laravel's pre-crafted components:

@component('mail::message')
# 発送のお知らせ

商品が発送されました!

@component('mail::button', ['url' => $url])
注文の確認
@endcomponent

ありがとうございました。<br>
{{ config('app.name') }} 様
@endcomponent

lightbulb">Tip!! Markdownメールを書く場合は、過剰なインデントを付けないでください。Markdownは段付をコードブロックとしてパースします。{tip} Do not use excess indentation when writing Markdown emails. Markdown parsers will render indented content as code blocks.

ButtonコンポーネントButton Component

ボタンコンポーネントは中央寄せのボタンリンクをレンダーします。このコンポーネントは引数として、urlとオプションのcolorを受け取ります。サポートしている色は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'])
注文の確認
@endcomponent

Panelコンポーネント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')
ここはパネルの内容です。
@endcomponent

Tableコンポーネント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       | テーブル      | 例       |
| ------------- |:-------------:| --------:|
| Col 2 is      | 中央寄せ      | $10      |
| Col 3 is      | 右寄せ        | $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

このコマンドにより、resources/views/vendor/mailディレクトリ下にMarkdownメールコンポーネントが公開されます。mailディレクトリ下に、htmlmarkdownディレクトリがあります。各ディレクトリは名前が示す形式で、利用できるコンポーネント全てのレスポンシブなプレゼンテーションを持っています。htmlディレクトリ下のコンポーネントは、HTMLバージョンのメールを生成するために使用され、もう一方のmarkdownディレクトリは平文テキストバージョンを生成するために使用します。これらのコンポーネントはお好きなように自由にカスタマイズしてください。This command will publish the Markdown mail components to the resources/views/vendor/mail directory. The mail directory will contain a html and a markdown directory, each containing their respective representations of every available component. The components in the html directory are used to generate the HTML version of your email, and their counterparts in the markdown directory are used to generate the plain-text version. 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 in-lined within the HTML representations of your Markdown mail messages.

lightbulb">Tip!! Markdownコンポーネント全体の新しいテーマを作成したい場合は、html/themesの中に新しいCSSファイルを記述し、mail設定ファイルのthemeオプションを変更します。{tip} If you would like to build an entirely new theme for the Markdown components, write a new CSS file within the html/themes directory and change the theme option of your mail configuration file.

メール送信Sending Mail

メッセージを送信するには、Mailファサードtoメソッドを使います。toメソッドはメールアドレス、ユーザーインスタンス、もしくはユーザーのコレクションを引数に取ります。一つのオブジェクト、もしくはオブジェクトのコレクションを渡すと、メーラは自動的にそれらのemailnameプロパティを使用します。そのため、オブジェクトで、その属性を確実に使用可能にしてください。送信先を指定し終えたら、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 setting the email 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\Order;
use App\Mail\OrderShipped;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Http\Controllers\Controller;

class OrderController extends Controller
{
    /**
     * 注文の配送
     *
     * @param  Request  $request
     * @param  int  $orderId
     * @return Response
     */
    public function ship(Request $request, $orderId)
    {
        $order = Order::findOrFail($orderId);

        // 配送処理…

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

メール送信時に"to"で受取人を指定するだけに限りません。"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 all within a single, chained method call:

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

MailableのレンダリングRendering Mailables

場合により、実際に送信はしないが、MailableのHTMLコンテンツを利用したいことも起きます。そのためには、Mailableのrenderメソッドを呼び出してください。このメソッドは、Mailableのコンテンツを評価し、文字列として返します。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 contents of the mailable as a string:

$invoice = App\Invoice::find(1);

return (new App\Mail\InvoicePaid($invoice))->render();

Previewing Mailables In The BrowserPreviewing Mailables In The Browser

mailableのテンプレートをデザインしているとき、Bladeテンプレートのようにブラウザでレンダし、簡単にレビューできると便利です。そのため、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\Invoice::find(1);

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

キュー使用メールQueueing Mail

メールメッセージのキューイングQueueing A Mail Message

メールメッセージを送ることにより、アプリケーションのレスポンス時間が極端に長くなり得るため、多くの開発者はメールメッセージをバックグランドで送信するためにキューイングすることを選びます。Laravelの統一されたキューAPIを使うことで、簡単に実現できます。メールメッセージをキューへ送るには、Mailファサードへ、受取人の指定の後に、queueメソッドを使います。Since sending email messages can drastically lengthen 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

メッセージを投入するキューを指定したい場合、laterOnメソッドを使用します。最初の引数に、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:

$when = now()->addMinutes(10);

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

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

make:mailコマンドにより生成されたmailableクラスにはすべて、Illuminate\Bus\Queueableトレイトが使用されています。接続とキュー名を指定する、onQueueonConnectionメソッドをすべてのmailableクラスインスタンスで呼び出せます。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のローカライズLocalizing Mailables

Laravelでは、現在のデフォルト言語とは別のローケルで、mailableを送信できます。メールがキュー投入されても、このローケルは保持されます。Laravel allows you to send mailables in a locale other than the current language, 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 is being formatted and then revert back to the previous locale when formatting is complete:

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

ユーザー希望のローケルUser Preferred Locales

ユーザーの希望するローケルをアプリケーションで保存しておくことは良くあります。モデルで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;
    }
}

このインターフェイスを実装すると、そのモデルに対しmailableや通知を送信する時に、Laravelは自動的に好みのローケルを使用します。そのため、このインターフェイスを使用する場合、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));

メールとローカル開発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. For more information on configuring your application per environment, check out the configuration documentation[/docs/{{version}}/configuration#environment-configuration].

全メールの送信先指定Universal To

Laravelが提供するもう一つの解決策は、フレームワークが送信する全メールの共通受け取り先を設定する方法です。この方法を使うと送信メッセージに指定した実際のアドレスの代わりに、アプリケーションが送る全メールを特定のアドレスに送信します。この方法を使用する場合、config/mail.php設定ファイルでtoオプションを指定します。Another solution provided by Laravel is to set a universal recipient of all emails sent by the framework. This way, all the emails generated by your application will be sent to a specific address, instead of the address actually specified when sending the message. This can be done via the to option in your config/mail.php configuration file:

'to' => [
    'address' => 'example@example.com',
    'name' => 'Example'
],

MailtrapMailtrap

最後の方法はMailtrapのようなサービスを使い、smtpドライバで本当のメールクライアントにより内容を確認できる「ダミー」のメールボックスへメールメッセージを送る方法です。このアプローチの利点は最終的なメールをMailtrapのメッセージビュアーで実際に確認できることです。Finally, you may use a service like 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.

イベントEvents

Laravelはメールメッセージ送信の過程で、イベントを2つ発行します。MessageSendingイベントは、メッセージが送信される前に発行され、一方のMessageSentイベントは、メッセージを送った後に発行されます。2つのイベントは、キューした時点でなく、メールが送信された時に発行されることを覚えておいてください。これらに対するイベントリスナは、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 an event listener for this event in your EventServiceProvider:

/**
 * アプリケーションへマッピングするイベントリスナ
 *
 * @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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作