How to send email with dynamic sender in laravel | Laravel Dynamic SMTP Email configurations

In Laravel, you can set up a dynamic SMTP (Simple Mail Transfer Protocol) configuration to send emails using a different SMTP server based on the current environment or based on the recipient's email address.

Here's an example of how you can set up a dynamic SMTP configuration in Laravel:

Step 1. Set Default SMTP Details on .env


MAIL_DRIVER=smtp
MAIL_HOST=smtp.example.com
MAIL_PORT=587
MAIL_USERNAME=sender@example.com
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls

Step 2. Create a new SMTP configuration array in the config/mail.php file. For example:

<?php
return [
    /*
    |--------------------------------------------------------------------------
    | Default Mailer
    |--------------------------------------------------------------------------
    |
    | This option controls the default mailer that is used to send any email
    | messages sent by your application. Alternative mailers may be setup
    | and used as needed; however, this mailer will be used by default.
    |
    */
    'default' => env('MAIL_MAILER', 'smtp'),
    /*
    |--------------------------------------------------------------------------
    | Mailer Configurations
    |--------------------------------------------------------------------------
    |
    | Here you may configure all of the mailers used by your application plus
    | their respective settings. Several examples have been configured for
    | you and you are free to add your own as your application requires.
    |
    | Laravel supports a variety of mail "transport" drivers to be used while
    | sending an e-mail. You will specify which one you are using for your
    | mailers below. You are free to add additional mailers as required.
    |
    | Supported: "smtp", "sendmail", "mailgun", "ses",
    |            "postmark", "log", "array", "failover"
    |
    */
    'mailers' => [
        'smtp' => [
            'transport' => 'smtp',
            'host' => env('MAIL_HOST'),
            'port' => env('MAIL_PORT'),
            'encryption' => env('MAIL_ENCRYPTION'),
            'username' => env('MAIL_USERNAME'),
            'password' => env('MAIL_PASSWORD'),
            'from' => [
                    'address'=> env('MAIL_FROM_ADDRESS'),
                    'name'=> env('MAIL_FROM_NAME'),
            ]
        ],    
    ],
    /*
    |--------------------------------------------------------------------------
    | Markdown Mail Settings
    |--------------------------------------------------------------------------
    |
    | If you are using Markdown based email rendering, you may configure your
    | theme and component paths here, allowing you to customize the design
    | of the emails. Or, you may simply stick with the Laravel defaults!
    |
    */
    'markdown' => [
        'theme' => 'default',
        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],
];

Step 3 : Store SMTP related Details on your related DB in Json Column Like below:


use App\Models\MailConfig;

public funciton store(Reuest $reuest){
    $smtpdetails=[
            'SMTP_NAME'=>(string)Str::uuid(),
            'MAIL_DRIVER'=>$request->MAIL_DRIVER??'',
            'MAIL_HOST'=>$request->MAIL_HOST??'',
            'MAIL_PORT'=>$request->MAIL_PORT??'',
            'MAIL_USERNAME'=>$request->MAIL_USERNAME??'',
            'MAIL_PASSWORD'=>$request->MAIL_PASSWORD??'',
            'MAIL_ENCRYPTION'=>$request->MAIL_ENCRYPTION??'',
            'MAIL_FROM_NAME'=>$request->MAIL_FROM_NAME??'',
        ];
    $request['smtp_details']=json_encode($smtpdetails);
    MailConfig::create($request);
}

Step 4: Create a new Service Provider class:

To create a new service provider class in Laravel, you can use the following

php artisan make:provider DynamicSMTPServiceProvider

This will generate a new service provider class in the app/Providers directory. The provider's name should DynamicSMTPServiceProvider

Step 5: Register the Provider:

Once the provider class is created, you need to register it in the config/app.php file. You can do this by adding the provider's class name to the providers array:.

'providers' => [
    ...
    App\Providers\DynamicSMTPServiceProvider::class,
],

Step 6: Define the boot method:

In the service provider class, you can also define the boot method. This method is used to bootstrap any custom functionality that your application requires.

<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Config;
use App\Models\MailConfig;
use Str;
class DynamicSMTPServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {       
        $smtpdata = MailConfig::select('smtp_details')->get();
        $arr = [];
        foreach ($smtpdata as $data) {
            $smtpdetails=json_decode($data->smtp_details);
            $smtpname=$smtpdetails->SMTP_NAME;
            $arr[$smtpname] = [
                'transport'=> $smtpdetails->MAIL_DRIVER,
                'host'=> $smtpdetails->MAIL_HOST,
                'port'=> $smtpdetails->MAIL_PORT,
                'encryption'=> $smtpdetails->MAIL_ENCRYPTION,
                'username'=> $smtpdetails->MAIL_USERNAME,
                'password'=> $smtpdetails->MAIL_PASSWORD,
                "from"=> [
                "address"=> $smtpdetails->MAIL_USERNAME,
                "name"=> $smtpdetails->MAIL_FROM_NAME,
                ]
            ];
        }
        $arr['smtp'] = [
            'transport'=> 'smtp',
            'host'=> env('MAIL_HOST'),
            'port'=> env('MAIL_PORT'),
            'encryption'=> env('MAIL_ENCRYPTION'),
            'username'=> env('MAIL_USERNAME'),
            'password'=> env('MAIL_PASSWORD'),
            'from'=> [
                    'address'=> env('MAIL_FROM_ADDRESS'),
                    'name'=> env('MAIL_FROM_NAME'),
            ]               
        ];
        Config::set('mail.mailers',$arr);
    }    
}

Step 7: Now Send Mail use your Controller

use Illuminate\Support\Facades\Mail;
use App\Models\MailConfig;

//Dynamic SMTP Method
public static function SendMailSMTP($id)
{
    $data = ['bodyMessage' => 'This is an example email message'];
    //Dynamic SMTP Details;
    $getsmtp=MailConfig::find($id);
    //Extract SMTP Details from DB;
    $smtpdetails=json_decode($getsmtp->smtp_details);   

    $smtpname=$smtpdetails->SMTP_NAME;
    $from=$smtpdetails->MAIL_USERNAME;
    $fromname=$smtpdetails->MAIL_FROM_NAME;
    $to='example@appetenza.in';
    $subject="Test Dynamic SMTP Mail";
    Mail::mailer($smtpanme)->send('emails.emailTemplate', $data, function($message) use($from,$fromname, $to, $subject)
    {
        $message->from($from,$fromname)->to($to)->subject($subject);
    });        
}

Comments

Leave a Reply