LoginSignup
1
0

More than 1 year has passed since last update.

LaravelのSMTPサーバを動的に設定する

Posted at

LaravelでSMTPサーバを設定するとき通常であれば.envに設定しますが、DBなどの動的な値を設定することができません。.env以外の方法を使ってSMTPサーバを動的に設定してみます。

環境

  • PHP: 8.0.3
  • Laravel: 8.65.0

手順

1. Mailableの生成

まずMailableを生成します。

php artisan make:mail Hoge

2. buildメソッドでSwiftMailerの上書きする

LaravelではSwiftMailerが使用されており、setSwiftMailerで上書きすることができます。1. で作成したMailableのbuildメソッド内で呼び出します。

app/Mail/Hoge.php
    public function build()
    {
        $config = # DBなどから設定情報を取得する

        /** @var \Illuminate\Mail\Mailer $mailer */
        $mailer = Mail::mailer();
        $transport = new Swift_SmtpTransport($config['mail_host'], $config['mail_port']);
        $transport->setUsername($config['mail_username']);
        $transport->setPassword($config['mail_password']);
        $mailer->setSwiftMailer(new Swift_Mailer($transport));
        $mailer->alwaysFrom($config['mail_from_address'], config('mail.from.name'));

        # 通常通りビューなどの設定を行う
        return $this->view('view.name');
    }

3. メールを送信する

あとはsendメソッドやqueueメソッドでメール送信、キュー投入すればOKです。

Mail::to('to_address@example.com')->send(new Hoge());
Mail::to('to_address@example.com')->queue(new Hoge());

没案:Providerを作る

$mailer->setSwiftMailerで行う上書き処理は必ずしもbuildメソッドで行う必要はないのですが、以下の理由からProviderで行うことは避けた方が良さそうでした。

  • キューでメールを処理する場合に対応できない
  • メールに関係のないリクエストのときにも処理が発生してしまう(この問題は遅延プロバイダを使えば解決できそうですが)

参考

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