Laravel Change Mail Driver Dynamically Example

Hello,

In this post, we will learn laravel change mail driver dynamically. let’s discuss about laravel change mail driver on the fly. This tutorial will give you a simple example of how to use multiple mail drivers in laravel. let’s discuss about laravel mailer example. Alright, let’s dive into the details.

You can use these tips with laravel 6, laravel 7, laravel 8 and laravel 9 versions.

You can define multiple mail drivers like smtp, ses, mailgun, postmark etc in laravel. You can also use that drivers dynamically to send using mailer() method. so let’s see the following example to send email with dynamic mail driver.

Define Multiple Mail Driver Configuration:

You need to go config/mail.php and set multiple connection as like the below:

config/mail.php

<?php

return [

...

...

'mailers' => [

'smtp' => [

'transport' => 'smtp',

'host' => env('MAIL_HOST', 'smtp.mailgun.org'),

'port' => env('MAIL_PORT', 587),

'encryption' => env('MAIL_ENCRYPTION', 'tls'),

'username' => env('MAIL_USERNAME'),

'password' => env('MAIL_PASSWORD'),

'timeout' => null,

'local_domain' => env('MAIL_EHLO_DOMAIN'),

],

'ses' => [

'transport' => 'ses',

],

'mailgun' => [

'transport' => 'mailgun',

],

'postmark' => [

'transport' => 'postmark',

],

....

Send Email Code:

You can follow the below tutorial to sending email from laravel. Then the below code i will show you how to send cc and bcc emails.

Follow Mail Sending Tutorial:Laravel Mail | Laravel Send Email Tutorial

.

.medrectangle-4-multi-155{border:none!important;display:block!important;float:none!important;line-height:0;margin-bottom:15px!important;margin-left:0!important;margin-right:0!important;margin-top:15px!important;max-width:100%!important;min-height:250px;min-width:300px;padding:0;text-align:center!important}

Send Email with Different Mail Driver:

You need to update the following controller code:

app/Http/Controllers/MailController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;

use Mail;

use AppMailDemoMail;

class MailController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

$mailData = [

'title' => 'Mail from ItSolutionStuff.com',

'body' => 'This is for testing email using smtp.'

];

Mail::mailer('postmark')

->to('[email protected]')

->send(new DemoMail($mailData));

Mail::mailer('mandrill')

->to('[email protected]')

->send(new DemoMail($mailData));

Mail::mailer('ses')

->to('[email protected]')

->send(new DemoMail($mailData));

dd("Email is sent successfully.");

}

}

I hope it can help you…

Leave a Comment