nitz25's avatar

Multiple emails

How to configure multiple email accounts in laravel? In .env I configured my email account like this

MAIL_DRIVER=smtp
MAIL_HOST=mail.x.com.ph
MAIL_PORT=587
MAIL_USERNAME=username
MAIL_PASSWORD=pass
MAIL_ENCRYPTION=tls

Is there another way to add another account when sending emails? Thanks

0 likes
4 replies
ctroms's avatar

You can create a second set of mail credentials in you .env file

MAIL2_HOST=some_host
MAIL2_PORT=some_port
MAIL2_USERNAME=some_user
MAIL2_PASSWORD=some_password
MAIL2_ENCRYPTION=tls

Then according to the SwiftMailerDocs, in your application create a new Swift_SmtpTransport instance

$swiftTransport = Swift_SmtpTransport::newInstance(env('MAIL2_HOST'), env('MAIL2_PORT'), env('MAIL2_ENCRYPTION'))
    ->setUsername(env('MAIL2_USERNAME' ))
    ->setPassword(env('MAIL2_PASSWORD' ));

The create a new Swift_Mailer instance

$swiftMailer = new Swift_Mailer($swiftTransport);

Then use the swift mailer setter in Laravel Mailer to assign the new swiftMailer instance. Laravel Mailer API

Mail::setSwiftMailer($swiftMailer);

At that point you should be able to use the Mail facade as you usually would to send with this new account.

Note: I didn't test this but it should work.

1 like
nitz25's avatar

Do I need to add another mail.php like other_mail.php under app/config? Or just use that in the controller? Cause when I dump the env('MAIL2_USERNAME') it returns null.

ctroms's avatar
ctroms
Best Answer
Level 15

@nitz25 You don't need another config for mail. You can set one up if you want and use the config helper function to access the values. You can put this code right in your controller or extract it to a helper function or separate class. It all depends on what your application needs.

Can you show your definition in your .env for both sets of mail variables?

**Please be sure to fill it out with dummy data and don't post any real usernames, passwords, etc in your reply. **

dd(env('MAIL2_USERNAME'));

should only return null if 'MAIL2_USERNAME' is not defined. Even if it is empty it will return an empty string.

BTW I did just try the code I posted in my first response and I am not having any issues.

Please or to participate in this conversation.