21
23

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 5.3 でメールを送る

Last updated at Posted at 2016-10-27

きっかけ

  • Laravelのドキュメントを読んでいたら Laravel 5.3Laravel 5.2 のメール関連のページ内容が全く違うことに気づいて、おう変わったんやな? と思いサンプル通りにやってみた。
  • Mailables? なんて訳せばいいのこれ(という感じなので本文はMailablesで押し通します)

Mailablesを作る

php artisan make:mail HogeShipped

Mailablesを書く

メモ

  • build メソッド内で各種設定をする感じっぽい。
  • HTMLメールの場合は view メソッド、プレーンテキストの場合は text メソッドを使う
    • ※今回はテキストメールを送りたいので text メソッドを利用
  • from メソッドは 1つ目の引数がメールアドレス、2つ目が表示名っぽい
  • このクラスの public なプロパティが view に渡るっぽいので、呼び出し側から渡せるようにコンストラクタの引数を設定

コード

app/Mail/HogeShipped.php
<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;

class HogeShipped extends Mailable
{
    use Queueable, SerializesModels;
    
    public $options;
    public $data;
    
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($options, $data)
    {
        $this->options = $options;
        $this->data = $data;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->from($this->options['from'], $this->options['from_jp'])
            ->subject($this->options['subject'])
            ->text($this->options['template']);
    }
}

送信部分を書く

メモ

  • オプションとデータを上のクラスに渡してあげる

コード

app/Http/Controllers/HogeController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Mail\HogeShipped;
use Mail;

class HogeController extends Controller
{
    public function send()
    {
        $options = [
            'from' => 'hoge@hogehogehogehoge.hoge',
            'from_jp' => 'ほげほげ',
            'to' => 'fuga@fugafugafugafuga.fuga',
            'subject' => 'テストメール',
            'template' => 'emails.hoge.mail', // resources/views/emails/hoge/mail.blade.php
        ];
        
        $data = [
            'hoge' => 'hogehoge',
        ];
        Mail::to($options['to'])->send(new HogeShipped($options, $data));
    }
}

メールテンプレートを書く

resources/views/emails/hoge/mail.blade.php
{{ $data['hoge'] }}

以上でたぶん送信できるはず。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?