Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ntbutler-nbcs's avatar

Using SMTP Mail Queues with Config Values in Database

Hi all!

I have been building a site on Laravel 12.x with various "system settings" stored in a custom database table - settings such as the SMTP host, port, encryption, auth username and auth password values.

I have a method in a controller that, when a particular request comes in, it will load those config values, setup the config state with those settings, and then send the SMTP mail successfully.

I am now trying to move the Mail::send command over to using Mail::queue to improve the responsiveness of the site, but I can't figure out how to get the database config to apply to messages when they are sent by the queue worker. When I have the queue worker running and then queue the message, it appears to try to load the config/mail.php config for the smtp mailer, but that only takes values from the .env file which I am not using.

On another thread, I did find mention of the Mail::build method to try to set the config into the message. However when I use that I then get errors in laravel.log sawing Mailer [ondemand] is not defined

 Mail::build([
    'transport' => 'smtp',
    'host' => $mailHost,
    'port' => $mailPort,
    'encryption' => $mailEncryption,
    'username' => $mailUsername,
    'password' => $mailPassword,
    'from' => [
        'address' => $mailFrom,
        'name' => $mailFromDisplayName
    ]
])->to( Auth::user() )->queue(new TestEmail);

[2025-04-10 10:17:07] testing.ERROR: Mailer [ondemand] is not defined. {"exception":"[object] (InvalidArgumentException(code: 0): Mailer [ondemand] is not defined. at /path/to/project/vendor/laravel/framework/src/Illuminate/Mail/MailManager.php:116)

So my question is how can I get the SMTP config loaded from the database to apply to emails sent by the queue worker? Again, it works OK when I load the config and send inside my controller, but not if I queue the messages.

0 likes
3 replies
Snapey's avatar

instead of directly queuing the mail, queue a job that sends the email ?

ntbutler-nbcs's avatar

Thanks @snapey that's exactly what I needed.

This was my first dig into queues and jobs, and I'd managed to get myself down the wrong track after finding some posts online that were queueing the emails directly. After your comment @snapey I found the following quick guide which I had working in just a few minutes.

medium.com/@bhuvaneshcj/mastering-laravel-10-mail-with-jobs-queues-a-comprehensive-guide-4e8e5c3bb1ef

Much appreciated!

Please or to participate in this conversation.