Laravel Use Multiple Email SMTP Mailers

In this article, we will discuss you how can configure multiple SMTP in your Laravel application to send emails.

Table of Contents

  1. SMTP Configuration
  2. Update .env File
  3. Usage

SMTP Configuration

Open config/mail.php and update your SMTP configuration:

mail.php
'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,
        // custom
        'allow_self_signed' => true,
        'verify_peer' => false,
        'verify_peer_name' => false,
    ],
    'smtp2' => [
        'transport' => 'smtp',
        'host' => env('MAIL_HOST_SMTP2', 'smtp.mailgun.org'),
        'port' => env('MAIL_PORT_SMTP2', 587),
        'encryption' => env('MAIL_ENCRYPTION_SMTP2', 'tls'),
        'username' => env('MAIL_USERNAME_SMTP2'),
        'password' => env('MAIL_PASSWORD_SMTP2'),
        'timeout' => null,
        // custom
        'allow_self_signed' => true,
        'verify_peer' => false,
        'verify_peer_name' => false,
    ],
    // rest config
],

Update .env File

Now, set your SMTP credentials in the .env file.

.env
# common
MAIL_MAILER=smtp
[email protected]
MAIL_FROM_NAME="${APP_NAME}"

# smtp 1 (default)
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_ENCRYPTION=null
MAIL_USERNAME=
MAIL_PASSWORD=

# smtp 2
MAIL_HOST_SMTP2=smtp.mailtrap.io
MAIL_PORT_SMTP2=2525
MAIL_ENCRYPTION_SMTP2=tls
MAIL_USERNAME_SMTP2=
MAIL_PASSWORD_SMTP2=

Usage

Finally, our app is ready to use two mail servers. Let's have a look at the usage:

// send using first mail server (default)
Mail::to('[email protected]')->send(new SendTestMail());
// or
Mail::mailer('smtp')->to('[email protected]')->send(new SendTestMail());

// send using second mail server
Mail::mailer('smtp2')->to('[email protected]')->send(new SendTestMail());

That's all. Thanks for reading. ๐Ÿ‘