Hello,
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:
config/mail.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',
],
....
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.
app/Http/Controllers/MailController.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 codecheef.org',
'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.");
}
}
Hope it can help you.
#laravel #laravel-9x #laravel-mail