How to set up multiple email configurations in Laravel?
There may be times when you need to send emails from different email addresses, for example, when a user creates an account in your application, you might want to send an email from accounts@example.com, and when something happens within your application, you might want to send an email from info@example.com. In this article, we’ll show you how to accomplish this requirement using Laravel.
Before we get started, we assume that you already know how to send emails and mail notifications with Laravel.
Step 1: Update your mail configuration file
Open your mail configuration file (config/mail.php
) and locate the global "from" address. Comment it out or remove it, as we will be defining it separately for each email configuration:
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
Next, add a new entry to the mailers
configuration array for each email configuration you need:
'mailers' => [
// This is the default configuration
'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,
],
// This is the second configuration, used to send info messages
'info' => [
'transport' => 'smtp',
'host' => env('INFO_MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('INFO_MAIL_PORT', 587),
'encryption' => env('INFO_MAIL_ENCRYPTION', 'tls'),
'username' => env('INFO_MAIL_USERNAME'),
'password' => env('INFO_MAIL_PASSWORD'),
'timeout' => null,
'auth_mode' => null,
'from' => [
'address' => env('INFO_MAIL_FROM_ADDRESS', 'info@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
],
// add more configurations if needed
],
Step 2: Update your .env
file
# Default mail configuration
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
# Second mail configuration
INFO_MAIL_MAILER=smtp
INFO_MAIL_HOST=smtp.mailtrap.io
INFO_MAIL_PORT=2525
INFO_MAIL_USERNAME=null
INFO_MAIL_PASSWORD=null
INFO_MAIL_ENCRYPTION=null
INFO_MAIL_FROM_ADDRESS=null
Step 3: Use the appropriate mail configuration
To send emails with the default configuration, use the Mail
facade:
Mail::to($recipient)->send(new OrderShipped($order));
To use a different mail configuration, specify the mailer using the mailer
method:
Mail::mailer('info')->to($recipient)->send(new OrderShipped($order));
And that’s it! You now know how to set up multiple email configurations in Laravel.