How do I use multiple from email configurations in my laravel app?
Question: in .env file we can configure only one email smtp details. How can I use multiple emails accounts and use their credentials for different scenarios.
My .env smtp setting
MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=xxxxxxxxx
MAIL_PASSWORD=xxxxxxxxxxxxx
MAIL_FROM_ADDRESS=sales@mywebsite.com
MAIL_FROM_NAME="Sales"
MAIL_ENCRYPTION=TLS
Below sends email but picks up configuration from .env file.
\Mail::to($firmAdminEmail->admin_email)->send(new AdminLeadAccept($acceptLink));
If this does not help, then I think you should have your .env
with each config like:
MAIL_SALES_USERNAME
, MAIL_SALES_PASSWORD
MAIL_SUPPORT_USERNAME
, MAIL_SUPPORT_PASSWORD
Then in the config you have this, so you can add new "senders" inside mailers
like this:
'sales' => [
'transport' => 'smtp',
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_SALES_USERNAME'),
'password' => env('MAIL_SALES_PASSWORD'),
'timeout' => null,
'auth_mode' => null,
],
'support' => [
'transport' => 'smtp',
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_SUPPORT_USERNAME'),
'password' => env('MAIL_SUPPORT_PASSWORD'),
'timeout' => null,
'auth_mode' => null,
],
So, before you send the email, you just select/change who you want to use as the sender:
Mail::mailer('support')
->to($request->user())
->send(new SupportTicketGenerated($ticket));
// Or
Mail::mailer('sales')
->to($request->user())
->send(new OrderShipped($order));
Read this part of the documentation about mailer
.