framework icon indicating copy to clipboard operation
framework copied to clipboard

[12.x] Allow queueing Mails by default

Open mpociot opened this issue 11 months ago • 4 comments

This PR adds the ability to automatically queue all outgoing mailables by default, no matter if they implement the ShouldQueue interface or not.

I think this method can be beneficial to prevent performance degradation (and application errors) by accidentally sending out mails synchronously that should always be sent via the queue.

The API works in a similar way to the DB::prohibitDestructiveCommands() method.

Usage (for example in your service provider):

<?php
class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Mail::queueMailsByDefault();
    }
}

Now, calling send will always queue the mail, regardless of the implemented interface. Of course, calling sendNow remains unaffected.

mpociot avatar Jan 20 '25 14:01 mpociot

There might be a bit more to think about here. 🤔 Should you be able to customize the connection and queue? What about notifications?

taylorotwell avatar Jan 20 '25 22:01 taylorotwell

I wonder if this should only impact HTTP requests?

Does it feel weird that mail send in queued jobs them become a new job?

timacdonald avatar Jan 21 '25 04:01 timacdonald

I personally often create a job that sends email instead of using Mailables as I often end up requiring more logic that Mailables cannot do or is obscure and the whole Address support mismatch between Mailable and Message. But we do use a direct email send when there's no need for any logic and with this option it would require using sendNow and all helper functions that run in jobs and being constantly aware that this is on as it will result in 2 jobs instead of one, potentially reducing the queues effectiveness. I suppose the solution will be to wrap this in !runningInConsole?

donnysim avatar Jan 21 '25 06:01 donnysim

Yeah I think it makes sense to only enforce queues when the application is not running via the CLI, like a queue worker.

@taylorotwell I like the idea to customize connection and queue. This would make it easy to enforce that all mails go through a specific queue.

The API could be something like:

Mail:: queueMailsByDefault(queue: 'emails', connection: 'sqs');

And if we do this, I think it would only make sense to have this on the Notification facade / NotificationSender as well.

What do you think?

mpociot avatar Jan 21 '25 08:01 mpociot