Laravel Mail Queue: change transport on fly

2.6k Views Asked by At

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

3

There are 3 best solutions below

5
Bogdan On BEST ANSWER

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) {
        //
    });
}
0
Franck On

Best way from notifications since Laravel 7 : https://laravel.com/docs/9.x/notifications#customizing-the-mailer

public function toMail($notifiable)
{
    return (new MailMessage)
                ->mailer('postmark')
                ->line('...');
}
0
Alejandro Morales On

I am working on a test where I need 300 different mailers (to fill Mailtrap Enterprise) so having 300 different configs was not good for me. I am posting the simple solution I found looking at Illuminate\Mail\Mailer class

$transport = Transport::fromDsn('smtp://user:pass@host:port');
Mail::setSymfonyTransport($transport);
Mail::to('[email protected]')
  ->send((new LaravelMail())
  ->subject('Subject')
);

Having this you can do some string manipulation to switch between transport configurations