set from email dynamically when sending mails in laravel

882 0 0 0

Last Updated : 2024-04-19 12:55:44

this snippet will teach you how to set different FROM EMAIL which exists in database to use as sender email when sending emails in laravel

after creating mailable file through this code


php artisan make:mail [wanted name of mail.php file] -m [specified view for blade file of the email itself] 
// for example
php artisan make:mail [welcomeMail] -m [emails.welcome]

the command above will create a welcomeMail.php in app\Mail folder and welcome.blade.php in resources\views\emails folder 


2- now you should modify build function to get email record from database and use it as sender's email in welcomeMail.php like this


<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

use App\Models\MessagesSetting ; // use this line to define model name


class newMessage extends Mailable
{
use Queueable, SerializesModels;

public $data ;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($data)
{
$this->email = $data['email'];
$this->subject = $data['subject'];
$this->message = $data['message'];

}

/**
* Build the message.
*
* @return $this
*/
public function build()
{
// use next 2 lines to get the email you want to set as sender's email in your application
$messagesSettings = MessagesSetting::find(1);
$fromMail = $messagesSettings->email;

return $this->markdown('emails.newMessage')
->from($fromMail) // use this line to determine the from email
-> with ([
'subject' => $this->subject ,
'message' => $this->message ,
]);
}
}

 

Mahmoud Anwar

Mahmoud Anwar

Back End Developer with a passion for developing innovative web applications that expedite the efficiency and effectiveness of organizational success. Well-versed in technology and writing code to create systems that are reliable and user-friendly. Also has the proven ability to motivate, educate, and collaborate effectively to build web applications and effectively track changes. Confident communicator, strategic thinker, and innovative creator to develop software that is customized to meet a company’s organizational needs, highlight their core competencies, and further their success.