Readouble

Laravel master メール

イントロダクションIntroduction

Laravelは人気の高いSwiftMailerライブラリーのクリーンでシンプルなAPIを提供しています。SMTP、Mailgun、SparkPost、Amazon SES、PHPのmail機能、sendmailドライバーを提供しており、選択したローカルやクラウドベースのサービスを使い、素早くメール送信が開始できるようにしています。Laravel provides a clean, simple API over the popular SwiftMailer[http://swiftmailer.org] library with drivers for SMTP, Mailgun, SparkPost, Amazon SES, PHP's mail function, 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',
],

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',
],

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

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'],

ビューの設定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',
                    ]);
    }

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($pathToFile) }}">
</body>

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

メール送信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"による受取人をすべて一つのメソッドチェーンで呼び出せます。Of course, 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));

キュー使用メール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. Of course, 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 = Carbon\Carbon::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
{
    //
}

メールとローカル開発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}}/installation#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はメールメッセージを送信する直前に、イベントを発行します。メールが実際に送信される場合に、このイベントを発行しますが、キューイングする場合には発行されないことに留意してください。EventServiceProviderへ、イベントリスナーを登録します。Laravel fires an event just before sending mail messages. Remember, this event is fired when the mail is 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\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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作