I'm using PHPMailer to send a newsletter out from a list of emails in a database. The script queries the database, puts the data into an array with a while loop, and in the while loop creates and sends the email.
It works fine until after 150 or so emails are sent, then it randomly stops. As an example, email blast #1 failed after 161 sent emails, email blast #2 failed after 165 sent emails, and email blast #3 failed after 182 sent emails.
I have been researching and researching and cannot find the cause to this. Right now I send each email in it's on To: message, and don't send them using the BCC: route. Could it be settings on my server? If so, what should I be looking for?
I also have a little bit of debugging built in. The sql script at the end adds the email to the database, along with the specific time it was sent, so that I can tell exactly how many get sent, which email stops the process, and how long it takes.
The emails it stops on show no pattern (meaning they are different email providers) and it only takes around 10 - 12 minutes to send out that many. My script timeout on the server is way high than that so that isn't the cause.
My code is as follows:
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "*server ip here*"; // specify main and backup server
$mail->SMTPKeepAlive = true; // SMTP connection will not close after each email sent
$mail->SMTPAuth = false; // turn on SMTP authentication
$mail->Username = "*user*"; // SMTP username
$mail->Password = "*pass*"; // SMTP password
while($select2 = sqlsrv_fetch_array($select)) {
$email = $select2['email'];
$unid = $select2['id'];
$unemail = $select2['email'];
$to = $email;
$from = "newsletter@site.com";
$new_date = date("n/j/y - g:i:s a");
$headers = "From: $from
";
$headers .= "MIME-Version: 1.0
";
$headers .= "Content-Type: text/html; charset=ISO-8859-1
";
$message2 = "<html><body>";
$message2 .= $message;
$message2 .= "</body></html>";
$mail->From = "newsletter@site.com";
$mail->FromName = "Newsletter";
$mail->AddAddress($to);
$mail->AddReplyTo("newsletter@site.com", "Website.com");
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = $subject;
$mail->Body = $message2;
if(!$mail->Send()) {
die("mail() Failed to send email to $to.");
echo "<br><br>Mailer Error: " . $mail->ErrorInfo;
exit;
} else {
$make_sent_query = "INSERT INTO emailssent (email_signup_id, email, datesent) VALUES (?, ?, ?)";
$params_sent = array($unid, $to, $new_date);
$add_to_sent = sqlsrv_query($conn, $make_sent_query, $params_sent);
if($add_to_sent) {
echo "Message sent for email $to<br>";
} else {
die("Mail sent, but failed to insert into Sent Emails database.");
}
}
$mail->ClearAddresses(); //clear addresses for next loop
}