Limit the number of messages sent on one SMTP connection - Laravel 5

Many SMTP servers have limits on the number of messages that can be sent during any one SMTP connection. If you are sending mail using the built in Mail class with Laravel, any messages sent within a request cycle are sent using one SMTP connection by default.

There is actually a quick and easy fix for this: activating the included AntiFlood Plugin on the underlying SwiftMailer libary that Laravel uses for SMTP. If you are using Laravel 5, then you already have everything you need.

How it's done

To call the method that activates the AntiFlood plugin, we need access to the SwiftMailer's class. This can be done with the getSwiftMailer() method that Laravel's Illuminate\Mail\Mailer class. (Remember that Mail is the facade for Illuminate\Mail\Mailer). Then we need to add the plugin, as shown in the SwiftMailer documentation. Below is what I came up with.

Mail::getSwiftMailer()->registerPlugin(new \Swift_Plugins_AntiFloodPlugin(100, 30));

The first parameter for the instantiation of the Swift_Plugins_AntiFloodPlugin class is the max number of emails to send per connection. The second parameter is the wait time, in seconds, between connections. The above example, will send the first 100 emails, end the connection, wait 30 seconds, and then begin the next 100 emails.

Other Plugins

It's worth noting that there are a few other plugins provided with the SwiftMailer library, one of which is similarly useful. Included is a Throttler Plugin that lets you set the rate at which emails are being sent. You can activate it with the same method explained above.