skip to Main Content

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('[email protected]')->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.

2

Answers


  1. Chosen as BEST ANSWER

    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('[email protected]')->subject($request->subject)->html('email body');
    
                $mailer->send($mailable);
            } 
    

  2. @itstare maybe this Laravel News can help you to find the way to work with.

    the reference discussion is from this Laracast

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search