Here is my code to send emails with PHPMailer.
It works seamlesly if mailto address is correct.
But if mailto address is incorrect or doesn't exist, the loop stops and will not deliver the rest of the emails on the database.
I guess that what happens is that $mailer->send()
throughs an error if email is incorrect, which makes it jump to the catch
and the sending of the email is not registered on the database (don't know why it jumps the update query though). This then loops for ever and nothing really happens.
Any ideas on how to fix?
If mailto address doesn't exist I just want to jump it and keep on with the rest of emails, or maybe, register it as sent = 'no'
and keep going with the rest.
//SEND EMAIL
$x = 1;
while ($x > 0) {
$result = $db->query("SELECT * FROM emails WHERE sent = '' AND mailto <> '' ORDER BY id ASC LIMIT 1");
if (mysqli_num_rows($result)==0) {
$x = 0;
} else {
$row = $result->fetch_assoc();
$id = $row["id"];
//Load email data
$mailer->AddAddress($row["mailto"]);
$mailer->Subject = $row["mailsubject"];
$mailer->Body = $row["mailbody"];
try {
//Send email
$mailer->send();
//Register email sent on db
$update = $db->query("UPDATE IGNORE emails SET sent='yes', date=now() WHERE id='$id'");
} catch (Exception $e) {
echo "Message could not be sent. Mailer Error: {$mailer->ErrorInfo}";
$mailer->getSMTPInstance()->reset(); //Reset the connection to abort sending this message.
}
//Clear all addresses and attachments for the next iteration
$mailer->clearAddresses();
$mailer->clearAttachments();
}
usleep(100000); //sleep for 0.1 seconds
continue;
}