How To Change Mail Driver Dynamically In Laravel


In this tutorial, I will show you how to change mail driver dynamically. If you don't know laravel change mail driver on the fly then this example is for you. Let's see how to use multiple mail drivers in laravel.  You know that we can define multiple mail drivers like smtp, ses, mailgun, postmark etc in laravel application dynamically. You can also use those drivers dynamically to send using the mailer() method. I will share with you the example of sending email with dynamic mail driver.

To do it we need to go to config/mail.php and set multiple connections as below:


return [
    'mailers' => [
        'smtp' => [
            'transport' => 'smtp',
            'host' => env('MAIL_HOST', ''),
            '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',


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


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',
            'body' => 'This is for testing email using smtp.'
                ->send(new DemoMail($mailData));
                ->send(new DemoMail($mailData));
                ->send(new DemoMail($mailData));
        dd("Email is sent successfully.");


Read also: How to Send Mail with PDF Attachment in Laravel


Hope it can help you.


#laravel #laravel-9x #laravel-mail