Laravel Change Mail Driver Dynamically Example

By Hardik Savani April 16, 2024 Category : Laravel

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, laravel 9, laravel 10 and laravel 11 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

.

Send Email with Different Mail Driver:

You need to update the following controller code:

app/Http/Controllers/MailController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Mail;

use App\Mail\DemoMail;

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('your_email@gmail.com')

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

Mail::mailer('mandrill')

->to('your_email@gmail.com')

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

Mail::mailer('ses')

->to('your_email@gmail.com')

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

dd("Email is sent successfully.");

}

}

I hope it can help you...

Tags :
Shares