'set mail driver dynamically from database for different email in notification

I want to set the following setting dynamically before I notify the user.

MAIL_DRIVER=
MAIL_HOST=
MAIL_PORT=
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_SENDER_EMAIL=
MAIL_SENDER_NAME=

for each customer they have the option to set this value from the frontend now I need to send email as per there setting is there any way in laravel I can do this.

I am using notification to notify each customer so before I notify I want to set this option dynamically from DB.

Thanks in advance.



Solution 1:[1]

these env variables then used in configuration file you can find right config names by checking mail.php in config folder

You can change config values at run time by array to config helper.

See: https://laravel.com/docs/6.x/configuration#accessing-configuration-values

You need to find corresponding variables and set their value like for Laravel - 6

config([
    'mail.driver' => 'smtp',
    'mail.host' => 'smtp.mailgun.org',
    'mail.port' => 587,
    'mail.encryption' => 'tls',
    'mail.username' => 'if-any',
    'mail.password' => 'if-any',
]);

After that your new settings should be used.

Solution 2:[2]

One alternative is to create a $mailer and use it, then discard it.

    $swiftMailer = app('mailer')->getSwiftMailer();

    $transport = $swiftMailer->getTransport()
        ->setUsername($username)
        ->setPassword($password)
        ->setHost($host)
        ->setPort($port)
        ->setEncryption($encryption)
        ->setTimeout(30);

    $mailer = app(\Illuminate\Mail\Mailer::class);
    $mailer->setSwiftMailer(new \Swift_Mailer($transport));
    $mailer->alwaysReplyTo($reply_to);
    $mailer->to($user->email)
        ->send(new AdminPasswordReset($data));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zohaib
Solution 2 Don Viegues