0
0

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 3 years have passed since last update.

LaravelでMailableクラスでメールを送信する方法

Last updated at Posted at 2020-12-06

【メモです。】

コントローラーの作成

php artisan make:controller SampleMailController

ルーティングの追加

Route::get('/mail', 'SampleMailController@send');

コントローラーに処理を追加

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Mail\SendTestMail;

use Mail;

class MailSendController extends Controller
{
    public function send()
    {
        $to = [
        [
            'email' => 'XXXXX@XXXXX.jp',
            'name' => 'Test',
        ]
    ];

        Mail::to($to)->send(new SendTestMail());
    }
}

Mailableクラスの作成

php artisan make:mail SendTestMail

SendTestMail.phpの編集

public function build()
{
    return $this->view('emails.test')
                ->from('XXX@XXXX','Test')
                ->subject('This is a test mail');
}

views/emailsの下にtest_text.blade.phpファイルを作成し、メール本文を記述

好きなように書けばOK

【余談】複数人にメールを送信したい場合

コントローラーの処理を下記のように変える。

$to = User::all();

Mail::to($to)->send(new SendTestMail());

【余談2】引数を渡す

コントローラーで下記のように引数に値を渡す。

$user = User::find(1);

Mail::to($user)->send(new SendTestMail($user));

あとはMailbleクラスの方で好きなように記述。

public function __construct($user)
    {
        $this->user = $user;
    }

    public function build()
    {
        return $this->text('emails.test_text')
                    ->from('XXX@XXXXX','Reffect')
                    ->subject('This is a test mail')
                    ->with(['user' => $this->user]);
    }
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?