I’m working on a Laravel project where I need to send emails with different SMTP credentials for each email. Instead of setting these credentials in the configuration files, I want to directly pass them to the Mail::mailer() method within my job.
Sometimes the configuration values are not set properly, and the email is sent using the credentials from the last email sent. Why does this happen, and how can I ensure that the correct credentials are always used?
Here is what I have so far:
class SendEmail implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct(
protected $recipient,
protected $content,
protected $subject,
protected $emailLog,
protected $emailDraftSettings,
protected $processedVideo,
) {
}
public function handle()
{
try {
// Change default mail sending config values
$emailDraftSettings = $this->emailDraftSettings;
config([
'mail.default' => 'smtp_email_sender',
'mail.mailers.smtp_email_sender.username' => $emailDraftSettings->from_email_id,
'mail.mailers.smtp_email_sender.password' => $emailDraftSettings->from_email_password,
'mail.from.address' => $emailDraftSettings->from_email_id,
'mail.from.name' => $emailDraftSettings->name
]);
Mail::to($this->recipient)
->send(new BusinessInquiryEmail($this->content, $this->subject));
$this->emailLog->is_email_sent = EmailLog::SENT;
$this->emailLog->save();
} catch (Exception $e) {
$this->emailLog->is_email_sent = EmailLog::FAILED;
$this->emailLog->failure_reason = $e->getMessage();
$this->emailLog->save();
Log::error('Error occurred while sending email: ' . $e->getMessage());
}
}
}
I expected each email to be sent with the correct SMTP credentials provided at runtime, without relying on the last used configuration values.
Jebin Joseph is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.