LoginSignup
1
1

More than 1 year has passed since last update.

Laravelのメールアドレス確認用メールのテンプレートを変更し、テキストメールで送信する

Posted at

Laravelのメールアドレス確認メールのテンプレート変更について、なかなか情報に行き当たらなかったので備忘録的に書いておきます。

対象バージョン

Laravel: 8.0

やりたかったこと

  • ユーザー登録後、メールアドレス確認用のメールを送信する
  • 送信したメールアドレスに確認用のURLを記載して、そのURLをクリックしたらサイトに飛ばす
  • 飛んだ先のサイトで認証し、メールアドレスを確認済みとする
  • このメールアドレス確認用メールをオリジナルのテキストメールにしたい

やったこと

  • この記事を参考に、メールアドレス確認メールの実装をした (認証自体もこの記事内になるURLを参考にしました)
  • この記事を参考に、テキストメール用のオーバーライドクラスを作成した
  • 公式 にある記事を参考に、AuthServiceProviderのbootに記述を追加した

参考になりそうなソースコード

app/Providers/AuthServiceProvider.php

<?php

namespace App\Providers;

use App\Services\MailService;
use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Notifications\Messages\MailMessage;

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

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array<class-string, class-string>
     */
    protected $policies = [
        // 'App\Models\Model' => 'App\Policies\ModelPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        // メールアドレス確認メールを変更
        VerifyEmail::toMailUsing(function ($notifiable, $url) {
            return (new TextMail)
                ->subject('メールタイトル')
                ->from(getenv('FROM_EMAIL_ENTRY'))
                ->to($notifiable->email)
                // テキストを選択、ビューと変数を指定できる
                ->text(
                    'email.email_verify_mail', [
                        'email' => $notifiable->email,
                        'url' => $url
                    ]
                );
        });
    }
}

// Mailableをオーバーライドしたクラス
class TextMail extends Mailable {
    use Queueable, SerializesModels;
    public function build() {}
}


1
1
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
1
1