In real-world development, email sending failures are a common issue. These could be caused by temporary mail server outages, network instability, or SMTP delays. To improve system reliability and avoid blocking the main process, we can use a queue to offload email sending to a background worker.
This tutorial uses Beanstalkd to demonstrate how to set up a PHP email queue.
First, install Beanstalkd:
sudo apt-get install beanstalkd
Start the service:
sudo systemctl start beanstalkd
Install the Beanstalkd PHP extension:
pecl install beanstalkd
Add the extension to your php.ini file:
extension=beanstalkd.so
Restart PHP-FPM service:
sudo systemctl restart php-fpm
Below is a basic example of a PHP class that queues and processes email jobs:
class MailQueue { protected $beanstalk; public function __construct() { $this->beanstalk = new PheanstalkPheanstalk('127.0.0.1'); } public function sendEmail($email, $subject, $message) { // Push email task to the queue $this->beanstalk->useTube('mail_queue')->put(json_encode([ 'email' => $email, 'subject' => $subject, 'message' => $message, ])); } public function handleEmails() { // Continuously listen and process the email queue while (true) { $job = $this->beanstalk->reserveFromTube('mail_queue'); $data = json_decode($job->getData(), true); // Email sending logic - implement actual email service here $this->sendEmail($data['email'], $data['subject'], $data['message']); // Delete job after processing $this->beanstalk->delete($job); } } }
Use the class to queue an email by calling the sendEmail method:
$mailQueue = new MailQueue(); $mailQueue->sendEmail('example@example.com', 'Email Subject', 'Email Body');
Supervisor is a common tool for managing long-running processes. Here's an example configuration to ensure your mail queue worker keeps running:
[program:mail_queue_worker] command=php /path/to/mail_queue_worker.php directory=/path/to/project user=www-data numprocs=1 autostart=true autorestart=true process_name=%(program_name)s_%(process_num)02d redirect_stderr=true
Make sure to replace /path/to/mail_queue_worker.php with the actual path to your worker script.
By using PHP in combination with a queue system like Beanstalkd, you can effectively prevent and recover from issues that commonly occur during email sending. This approach promotes better system decoupling, improves performance, and ensures higher availability. The provided example walks through setup, implementation, and deployment, making it a solid foundation for managing emails in PHP applications.