6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel Mail

6
Posted at

Laravel のメールパッケージについて

概要 

メールを送信するパッケージ

使うべき理由としては、

  • キューシステムとの連携。
  • Viewを使ったメールテンプレートの取り扱い
  • Swift_Transportベースの多様なメールサービスサポート

などがあげられる。

デフォルトでは、Mailgun, Mandrill, SparkPost, SES に対応している。

但し、キューと送信は別になっているので適宜ラップする必要はありそう。

使用方法

Mail ファザードを利用。コンテナから直接取るときは、app("mailer")。クラス名での登録はない模様。

型はIlluminate\Contracts\Mail\Mailerで落ちてくる。

Mail::send('emails.reminder', ['user' => $user], function ($m) use ($user) {
    $m->from('hello@app.com', 'Your Application');
    $m->to($user->email, $user->name)->subject('Your Reminder!');
});

第一引数にmailのviewテンプレート名を、第二引数にViewで使用する変数を、第三引数にはメールを操作するためのクロージャを用意する。

クロージャには \Illuminate\Mail\Messageが落ちてくる形で、fromtoと言った情報をここでセットする。

キューを使用する

Mail::queue('emails.welcome', $data, function ($message) {
    //
});

メールをキューにセットする時には、queueメソドを使用する。引数の取り方は同じで、第四引数にキューの名前を指定する事もできるよう。

ちなみにqueueはContractに無いのでContractでタイプヒントとっている時には要注意。

最後に

Transportの拡張とかも楽ちんっぽいので、Laravel系列での開発では便りになりそう。

Config 参照している箇所がもうちょっとなんとかなればなぁ…という気もするが…

6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?