How to conditionally change the mail transporter in laravel 5?

I am using laravel 5.3. I need to send mail with different credentials (host, port, username, password).

I can send the default laravel config (.env).

But I need a dynamic level implementation.

I create a config array,

   // Pre-Mail Setup Config.
            $store_config = [
              'list' =>  
                  //SET 1
                 ['from_name' => 'sender1',
                'from_address' => 'from_adderss1',
                'return_address' => 'reply1',
                'subject' => 'subject1',
                'host' => 'host1',
                'port' => 'post1',
                'authentication' => 'auth1',
                'username' => 'uname1',
                'password' => 'pass1'],
                 //SET 2
                [.........],
                 //SET 3
                [.........]
            ];

I am trying to send a message, but this will not work.

 // Inside Foreach.
$transporter = \Swift_MailTransport::newInstance('smtp.gmail.com', 465, 'ssl')
                ->setUsername($config['username'])
                ->setPassword($config['password']);

$mailer = \Swift_Mailer::newInstance($transporter);


$message->from($config['from_address'], $config['from_name']);


$message->to('To_Email, 'Name')
        ->subject('My Subject')
        ->setBody('My Content', 'text/html');
$mailer->send($message);

What is wrong with my code?

Is it possible?

Or any other solution?

+4
source share
1 answer

Finally, I found a way to solve this problem.

In fact, Laravel 5 does not fully support this configuration of multiple transporters.

therefore, I use an alternative package to achieve it.

My code

    foreach ($store_configs['list'] as $store_config) {

        // Create Custom Mailer Instances.
        $mailer = new \YOzaz\LaravelSwiftmailer\Mailer();
        $transport = \Swift_SmtpTransport::newInstance(
                                           $store_config['host'], 
                                           $store_config['port'], 
                                           $store_config['authentication']);

        // Assign Dynamic Username.
        $transport->setUsername($store_config['username']);

        // Assign Dynamic Password.
        $transport->setPassword($store_config['password']);
        $smtp = new \Swift_Mailer($transport);
        $mailer->setSwiftMailer($smtp);



            $mailer->send('template', ['data'], function ($message) use ($queue) {
                // Default Response goes here
                $message->from('From Address', 'From Name');

                $message->to($email, 'Name')->subject('My Subject')
                    ->setBody('My HTML', 'text/html');
                $message->getSwiftMessage();
                //
            });
   }

.

!

0

Source: https://habr.com/ru/post/1664885/


All Articles