Using multiple email smtp mailers in Laravel

Laravel-8 multiple smtp
Using multiple smtp configurations in laravel 8

Sometimes in your application, you may need to use more than one mail drivers to cover different areas, but Laravel 5.3 only supports one,

how can we extend it to support more mail drivers and be able to switch the drivers at runtime?

Check below code, I have tried it and its working perfect for my application.

In this tutorial we will discuss you how can configure multiple smtp in your Laravel applications to send emails.

Steps to configure multiple emails

Step 1: Add your smtp configurations

'mailers' => [
'smtp' => [
'transport' => 'smtp',
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'auth_mode' => null,
],

'smtp2' => [
'transport' => 'smtp',
'host' => env('SMTP2_MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('SMTP2_MAIL_PORT', 587),
'encryption' => env('SMTP2_MAIL_ENCRYPTION', 'tls'),
'username' => env('SMTP2_MAIL_USERNAME'),
'password' => env('SMTP2_MAIL_PASSWORD'),
'timeout' => null,
'auth_mode' => null,
],
// your other email configurations
]

Step 2. Add your smtp settings in .env file

//smtp configurations
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=someemail@somedomain.co.nz
MAIL_PASSWORD=youremailpassword
MAIL_ENCRYPTION=ssl
//smtp2 configurations
SMTP2_MAIL_HOST=smtp.anothermail.com
SMTP2_MAIL_PORT=465
SMTP2_MAIL_USERNAME=someemail@somedomain.co.nz
SMTP2_MAIL_PASSWORD=youremailpassword
SMTP2_MAIL_ENCRYPTION=ssl

Step 3. Then you can directly use

//to send using first smtp configurations
Mail::mailer('smtp')->to('receiver@mail.com')->send(new TestMail());
//to send using seconds smtp configurations
Mail::mailer('smtp2')->to('receiver@mail.com')->send(new TestMail());

You can also use this with your mail jobs or queues as same in step 3.

Don't forget to reload your configuration before testing.

I believe this brief tutorial will be of much help. Do not forget to share this tutorial your friends. Don’t forget to leave your comments below, if you have any. Love Leads!!!

Software Developer, developing desktop, web and mobile applications using Java, PHP, Spring, Laravel and React.