With the development of the internet, email has become an indispensable part of daily communication. However, when business grows rapidly and the number of users increases, sending a large volume of emails directly can lead to server performance degradation or email delivery failures. To avoid these issues, using a mail queue system can efficiently manage email sending through serial processing.
The workflow of a mail queue system is as follows:
Implementing a simple PHP mail queue system typically involves the following steps:
Below is a simple PHP mail queue system code example:
// Create mail queue table<br>$database->query("CREATE TABLE IF NOT EXISTS email_queue (<br> id int(11) NOT NULL AUTO_INCREMENT,<br> to varchar(255) NOT NULL,<br> from varchar(255) NOT NULL,<br> subject varchar(255) NOT NULL,<br> body text NOT NULL,<br> attachment varchar(255) DEFAULT NULL,<br> status enum('pending','sent','failed') NOT NULL DEFAULT 'pending',<br> PRIMARY KEY (id)<br>)");
// Enqueue email<br>$to = "recipient@example.com";<br>$from = "sender@example.com";<br>$subject = "Email Subject";<br>$body = "Email Body";<br>$attachment = "path/to/attachment.pdf";<br>$database->query("INSERT INTO email_queue (to, from, subject, body, attachment) VALUES ('$to', '$from', '$subject', '$body', '$attachment')");
// Email sending script<br>$sql = "SELECT * FROM email_queue WHERE status='pending' LIMIT 1";<br>$email = $database->query($sql)->fetch();
if ($email) {<br> // Send email<br> if (send_email($email['to'], $email['from'], $email['subject'], $email['body'], $email['attachment'])) {<br> // Update status to sent if successful<br> $database->query("UPDATE `email_queue` SET `status`='sent' WHERE `id`='$email[id]' ");<br> } else {<br> // Update status to failed if sending fails<br> $database->query("UPDATE `email_queue` SET `status`='failed' WHERE `id`='$email[id]' ");<br> }<br>}
In this example, we use MySQL as the database to store mail queue information. When an email is enqueued, its details are inserted into the database table. The email sending script periodically checks the queue and processes pending emails. If sent successfully, the status updates to "sent"; if failed, it is marked as "failed".
By implementing a PHP mail queue system, we can not only improve the efficiency of email sending but also prevent server crashes under high load. Additionally, the mail queue system provides better error handling mechanisms such as automatic retries and failure logging. For scenarios requiring sending large volumes of emails, this system greatly increases the success rate and makes management more convenient.
If you want to further extend this system, you can consider adding features like email sending priority and delayed sending, which can enhance the system’s flexibility and scalability.