3_2_メール送信時のcontroller・mailableクラスの変数の書き方 - hpscript/laravel GitHub Wiki

  • to, cc, bccなど宛先はcontrollerで書く
  • mailableクラスのコンストラクターに引数を渡す
  • constructorに初期値を設定し、callback関数でルートからプレビューを行うこともできる
  • メール本文は、text, htmlどちらも可能。改行はbrタグ

controller

use Illuminate\Support\Facades\Mail;
use App\Mail\TestMail;
public function index()
    {
        //
        $name = '山本太郎';
        $date = '2020/02/11';
        $status = '完了';
        $to = '[email protected]';
        $cc = '[email protected]';
        
        Mail::to($to)
            ->cc($cc)
            ->send(new TestMail($name, $date, $status));
        return "its works";
    }

app/Mail/TestMail.php

$ php artisan make:mail TestMail

public function __construct($name='山田太郎', $date='2020/01/01', $status='テスト')
    {
        //
        $this->title = $date . 'テスト送信';
        $this->date = $date;
        $this->name = $name;
        $this->status = $status;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this
            ->from('[email protected]')
            ->subject($this->title)
            ->view('email.test')->with([
                'name' => $this->name,
                'date' => $this->date,
                'status' => $this->status,
            ]);
    }

view

{{ $date }}<br>
メール本文<br>
{{ $name }}さんのステータスは{{ $status}}です

routeプレビュー時

Route::get('/send', 'MailController@index');
Route::get('/send/preview', function(){
	return new App\Mail\TestMail();
});

sakura

MAIL_DRIVER=smtp
MAIL_HOST=${domain}.sakura.ne.jp
MAIL_PORT=587
MAIL_USERNAME=laravel@${domain}.sakura.ne.jp
MAIL_PASSWORD=${password}
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=laravel@${domain}.sakura.ne.jp
MAIL_FROM_NAME=Example