Phpmailer - Sending emails is possible?

Asked

Viewed 69 times

3

Is there any implementation that can be done on PHPMailer so that emails that could not be sent (due to the momentary fall of the server of the site that uses the PHPMailer, for example) can be sent later?

It may be some kind of monitoring of the mail server or recording of emails to be sent (check whether they were sent or not).

2 answers

3

What you can do here is create a table in the database with the emails that were not sent and by a cron every hour for example, or the interval you want to try to resend the pending emails.

0

The method Send() class returns a Boolean that will be false if the message is not sent for any reason.

<?php
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "smtp1.example.com;smtp2.example.com";
$mail->SMTPAuth = true;
$mail->Username = 'smtpusername';
$mail->Password = 'smtppassword';

$mail->AddAddress("[email protected]");
$mail->Subject = "assunto";
$mail->Body = "PHPMailer.";

if(!$mail->Send())
{
   echo "Erro: " . $mail->ErrorInfo;
}
else
{
   echo "E-mail enviado";
}
?>

You can use an infinite loop to keep trying to send, but this is not a good practice because the application can get stuck in it trying to send without success, so I used a for limiting the number of attempts to 10, each attempt is spaced in 30 seconds.

for($tentativas = 0; $tentativas < 10; $tentativas++){
    if($mail->Send())
    {
       break;
    }
    sleep(30);
}
  • Icardo this is not a very good idea... I would get the application stuck in it until he could send it. The best would be to have a cron running x in x time trying to send pending emails.

  • @Jorgeb. he can limit the number of attempts, I’ll add that now

  • Ricardo but this does not solve anything. If the server is low the probability of all fail is huge.

  • @Jorgeb. What would be "the server is down"?

  • @This loop of attempts I’ve seen in other sources and helps a lot. The bigger question would be in relation to when the server goes down (that’s what Jorgeb. must mean by 'server below'. There would be pending emails whose sending attempts failed. Still, thank you for the replies.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.