LoginSignup
25
18

More than 5 years have passed since last update.

[laravel]Notificationを使ってメール送るときにMailableを使う

Last updated at Posted at 2018-04-26

 やりたいこと

公式の「メール通知」の「他の通知フォーマットオプション」でMailableを使うやり方が紹介されているが、あまりに簡素な説明になってしまっているので、具体的なやり方を確認する。

環境

Laravel 5.5

何が嬉しいか

通常はMailMessageインスタンスを使うが、これだと必要最低限のことしかできない。MailableインスタンスだとMailMessageインスタンスではできなかった以下のようなことができるようになる。
- テキストメールを送れる。
- SwiftMailerに好き勝手にパラメータを渡せる。
 - return-pathが設定できる。
 - x-mailerのような拡張ヘッダを追加できる。

Mailファサード使ってsend()すれば良いじゃん

それだとnotify()ではなくsend()になり、「通知」のコンテキストが損なわれるのでやりたくない。

やってみた

まずMailableクラスを直接インスタンスとして利用しようとすると、build()が実装されてないっていう旨のエラーが吐かれる。そのため、継承してbuild()するだけのクラスをapp/Email内に新規作成する。

app/Email/Notification.php
<?php

namespace App\Mail;

use Illuminate\Mail\Mailable;

class Notification extends Mailable
{
    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        //
    }
}

次に作成したNotificationクラスを通知用のクラスのtoMailメソッドで呼び出すようにする。

変更前

ヘッダを自由に設定できず、テキストメールを作ることもできなかったため、ヘッダの拡張は諦めつつmarkdownで送っている。

php
public function toMail($notifiable)
{
    return (new MailMessage)
        ->from(config('mail.from.address'))
        ->subject('メッセージ受信通知')
        ->markdown('emails.message_received', ['url' => route('hoge')]);
}

変更後

ヘッダにreturn-pathx-Mailerを設定して、テキストメールを作って送れるようになった。

app/Notifications/SampleNotification.php
public function toMail($notifiable)
{
    return (new \App\Mail\Notification())
        ->text('emails.message_received', ['url' => route('hoge')])
        ->from(config('mail.from.address'))
        ->to($notifiable->email)
        ->subject('メッセージ受信通知')
        ->withSwiftMessage(function (\Swift_Message $message) {
            $message
                ->setReturnPath(config('mail.from.address'))
                ->getHeaders()->addTextHeader('X-Mailer', 'hoge-mailer');
        });
}

以上。

共通でセットするパラメータであれば、build() 内でreturn $this->from(config('mail.from.address')) とかしても良さそう。

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