Laravel Mail Queue: change transport on fly

▼魔方 西西 提交于 2019-12-11 00:06:10

问题


I'm trying to use different SMTP configuration for each user of my application. So, using Swift_SmtpTransport set a new transport instance, assign it to Swift_Mailer and then assign it to Laravel Mailer.

Below the full snippet:

$transport = Swift_SmtpTransport::newInstance($mailConfig['smtp_host'], $mailConfig['smtp_port'], 'ssl');
$transport->setUsername($mailConfig['smtp_user']);
$transport->setPassword($mailConfig['smtp_pass']);
$smtp = new Swift_Mailer($transport);
Mail::setSwiftMailer($smtp);
Mail::queue(....);

Messages are added to the queue but never dispatched. I guess that since the "real" send is asyncronous it uses default SMTP configuration, and not the transport set before Mail::queue().

So, the question is: how to change mail transport when using Mail::queue()?


回答1:


Instead of using Mail::queue, try creating a queue job class that handles sending the email. That way the transport switching code will be executed when the job is processed.

The Job Class Structure Documentation actually uses a mailing scenario as an example, which receives a Mailer instance that you can manipulate. Just use your code in the class's handle method:

public function handle(Mailer $mailer)
{
    $transport = Swift_SmtpTransport::newInstance($mailConfig['smtp_host'], $mailConfig['smtp_port'], 'ssl');
    $transport->setUsername($mailConfig['smtp_user']);
    $transport->setPassword($mailConfig['smtp_pass']);
    $smtp = new Swift_Mailer($transport);

    $mailer->setSwiftMailer($smtp);

    $mailer->send('viewname', ['data'], function ($m) {
        //
    });
}


来源:https://stackoverflow.com/questions/34809669/laravel-mail-queue-change-transport-on-fly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!