Cron‑Based Email Sending
Triggering email delivery during a web request delays the response and risks losing messages if the process times out. By queuing emails and sending them in batches via cron, you ensure reliability and responsiveness.
Queueing messages
Insert emails into a database queue table with fields for recipient, subject, body and status:
CREATE TABLE email_queue (
id INT AUTO_INCREMENT PRIMARY KEY,
recipient VARCHAR(255) NOT NULL,
subject VARCHAR(255) NOT NULL,
body TEXT NOT NULL,
status ENUM('pending','sent','failed') DEFAULT 'pending',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
Instead of calling mail() directly, insert a row into email_queue and commit your transaction.
Sending queued mail
Create a CLI script that runs on a schedule and processes pending rows:
<?php
declare(strict_types=1);
$pdo = new PDO('mysql:host=localhost;dbname=app', 'user', 'pass');
$stmt = $pdo->prepare('SELECT * FROM email_queue WHERE status = "pending" LIMIT 50');
$stmt->execute();
foreach ($stmt as $row) {
// use your favourite mailer library
$sent = sendEmail($row['recipient'], $row['subject'], $row['body']);
$update = $pdo->prepare('UPDATE email_queue SET status = :status WHERE id = :id');
$update->execute([
'status' => $sent ? 'sent' : 'failed',
'id' => $row['id'],
]);
}
?>
Schedule the script using cron: */5 * * * * php /path/to/send_emails.php. Tune the frequency and batch size to suit your traffic.