Using the Throttler Plugin
The Throttler Plugin – like all plugins – is added with the Mailer class' registerPlugin() method. It has two required constructor parameters that tell it how to do its rate-limiting.
To use the Throttler plugin:
- Create an instance of the Mailer using any Transport you choose.
- Create an instance of the Swift_Plugins_ThrottlerPlugin class, passing the number of emails, or bytes you wish to limit by, along with the mode you're using.
- Register the plugin using the Mailer's registerPlugin() method.
- Continue using Swift Mailer to send messages as normal.
When Swift Mailer sends messages it will keep track of the rate at which sending messages is occuring. If it realises that sending is happening too fast, it will cause your program to sleep() for enough time to average out the rate.
Both batchSend() and send() methods will work with this plugin.
<?php
require_once 'lib/swift_required.php';
//Create the Mailer using any Transport
$mailer = Swift_Mailer::newInstance(
Swift_SmtpTransport::newInstance('smtp.example.org', 25)
);
//Rate limit to 100 emails per-minute
$mailer->registerPlugin(new Swift_Plugins_ThrottlerPlugin(
100, Swift_Plugins_ThrottlerPlugin::MESSAGES_PER_MINUTE
));
//Rate limit to 10MB per-minute
$mailer->registerPlugin(new Swift_Plugins_ThrottlerPlugin(
1024 * 1024 * 10, Swift_Plugins_ThrottlerPlugin::BYTES_PER_MINUTE
));
//Continue sending as normal
for ($lotsOfRecipients as $recipient) {
...
$mailer->send( ... );
}
Parent topic: Throttler Plugin