1. Optimized PHPMailer Bulk Sending Code
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'vendor/autoload.php';
$mail = new PHPMailer(true);
try {
// Server settings
$mail->isSMTP();
$mail->Host = 'relay.171mails.com';
$mail->SMTPAuth = true;
$mail->Username = 'your_171mails_username';
$mail->Password = 'your_171mails_password';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
$mail->SMTPKeepAlive = true; // REUSE CONNECTION
$mail->setFrom('newsletter@yourdomain.com', '171mails Updates');
$mail->isHTML(true);
$mail->Subject = 'Monthly Community Update';
$mail->Body = '<h1>Welcome!</h1><p>Your monthly content digest.</p>';
// Loop through recipient database
foreach ($subscribers as $sub) {
$mail->addAddress($sub['email'], $sub['name']);
$mail->send();
$mail->clearAddresses(); // Reset for next subscriber
usleep(100000); // 100ms pacing delay (10 emails/sec)
}
$mail->smtpClose(); // Gracefully close connection
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
} 2. The Importance of SMTPKeepAlive
Without SMTPKeepAlive = true, PHPMailer opens a new TCP connection, executes a TLS handshake, authenticates with username/password, and closes the connection for every single recipient. This generates enormous latency. Keeping the socket alive accelerates delivery speed by up to 500%.
3. Handling PHP Script Execution Timeouts
Long-running CLI scripts should execute via PHP CLI rather than web servers (Apache/Nginx). Use set_time_limit(0) and monitor memory consumption using memory_get_usage() to ensure stability across large dispatches.