phplaravellaravel-maillaravel-config

Change Laravel mail configuration during runtime


I need to change Laravel Mail Configuration during the runtime. This is because the configuration needs to be changed several times during runtime, not just once on app initialization.

foreach ($emails as $email) {
    Config::set('mail.mailers.smtp.username', $email->email);
    Config::set('mail.mailers.smtp.password', $email->password);
    Config::set('mail.from.address', $email->email);

    Mail::to('someone@example.com')->send(new DemoMail('title', 'body'));
}

As you can see, I am trying to set new configurations on each iteration, but the configuration is only set once (on the first iteration); all other emails are sent using the design from the first iteration.

I have found solutions using Service Providers. Similar to this one Dynamic mail configuration with values from database [Laravel] The problem is that the provider sets mail configuration when the app is initialized and can't be changed during runtime. So this doesn't solve my problem.

The second idea I came up with is to define multiple mail drivers (configurations), one for each email, and then use the mailer() function to specify which one I want to use on each iteration. The problem with this solution is that I need to create those drivers dynamically; I can't hardcode them.

I searched the internet for the right solution, but couldn't find one.


Solution

  • I have found a solution by using Symfony Mailer in Laravel.

    foreach ($emails as $email) {
                $transport = new EsmtpTransport('mail.host', 465);
                $transport->setUsername($email->email);
                $transport->setPassword($email->password);
    
                $mailer = new Mailer($transport);
    
                $mailable = (new SymfonyEmail())->from($email->email)->bcc('test@test.com')->subject($request->subject)->html('email body');
    
                $mailer->send($mailable);
            }