PHP and PHPMailer: How to Check if Your Mail Send Failed CodeUnit 21 DEC 2011

PHPMailer is a great little mail sending workhorse class for PHP, widely expanding on the regular PHP mail() function and particularly easy to make use of, making it a personal favourite of mine.

Anyway, to check whether or not your mail send was successful when using PHPMailer, all you need to do is check the Boolean variable returned by the Send() function, and if false, check what the error message contained in ErrorInfo is.

In practice:

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@example.com");
$mail->Subject = "Test 1";
$mail->Body = "Test 1 of PHPMailer.";

if(!$mail->Send())
{
   echo "Error sending: " . $mail->ErrorInfo;
}
else
{
   echo "E-mail sent";
}

As simple as that! :)

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.

  • Mostafa

    i’ve used the above code exactly, and it sent a message that email was sent, however nothing received, since i’ve emailed it to myself, could you please advise what possibly went wrong?

    • Hi Mostafa. Most likely there is an issue with your SMTP credentials. A good place to look might be in the PHP error log itself.

  • Apit Mahmood

    Hi Craig,

    this is my code:

    $arrReceipen = explode(“,”,$receipen);
    foreach($arrReceipen as $rp)
    {
    $mail->addAddress($rp);
    }

    how to check each one e-mail sent or not..?

    • Hi Apit. The short answer is that you can’t. You code indicates a single mail being sent (the mail server will send out to the multiple addresses). PHP can only report whether or not the mail reaches the mail server – if it does, then it is considered to have been ‘sent’. (Or rather, I don’t think that you can get what you are after.)

      • Apit Mahmood

        ok thanks Craig for your info..have a nice day