2
3

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.

Laravel5.3でユーザ登録時にメール送信

Last updated at Posted at 2016-11-28

##新サービスをLaravel5.3で立ち上げる事にしたので備忘録
勉強する時間も無いのだけど…とにかくググって実装!
まずは標準のAuthを使えるようにする。

laravel/
php artisan migrate
php artisan make:auth

本題の登録時にメール送信は、5.1とかのやり方とか見つけれたのですが、どうも動かない…
自分なりに読み解いて下記対応で完成とすることにした。

###Config確認

config/app.php
'aliases' => [
        'Mail' => Illuminate\Support\Facades\Mail::class,

##方法1
###Controller

RegisterController.php
use Mail;  //aliasesが設定されているとそのまま宣言できる。

~~

// functionなり作って実行
Mail::send(
    'emails.done', // テンプレートファイル呼び出せる
    ['user' => $user],
    function($message) use ($user) {
        $message->to($user->email)->bcc('bcc@example.com')->subject('登録完了のお知らせ');
    }
);

###View

emails/done.blade.php
<p>ようこそ{{ $user['name'] }} さん</p>

##方法2

laravel/
php artisan make:mail DoneMail
DoneMail.php
<?php

namespace App\Mail;

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

class DoneMail 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'])
            ->bcc($this->options['bcc'])
            ->subject($this->options['subject'])
            ->view($this->options['template']);
    }
}

###Controller

RegisterController.php
use App\Mail\DoneMail;
use Mail;  //aliasesが設定されているとそのまま宣言できる。

~~

// functionなり作って実行
$options = [
    'from' => 'from@example.com,
    'from_jp' => '【○○より',
            'to' => $mail_to,
            'subject' => '登録完了のお知らせ',
            'template' => 'emails.done'
        ];

        $data = [
            'mail_to' => $mail_to,
        ];
        Mail::to($mail_to)->send(new DoneMail($options, $data));

###View

emails/done.blade.php
<p>ようこそ{{ $user['name'] }} さん</p>


Facades…
Contracts…
う~ん…

2
3
2

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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?