phplaravelswiftmailermail-queue

Laravel Mail Queue: change transport on fly


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()?


Solution

  • 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) {
            //
        });
    }