Error handling with PHPMailer Error handling with PHPMailer php php

Error handling with PHPMailer


PHPMailer uses Exceptions. Try to adopt the following code:

require_once '../class.phpmailer.php';$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catchtry {  $mail->AddReplyTo('name@yourdomain.com', 'First Last');  $mail->AddAddress('whoto@otherdomain.com', 'John Doe');  $mail->SetFrom('name@yourdomain.com', 'First Last');  $mail->AddReplyTo('name@yourdomain.com', 'First Last');  $mail->Subject = 'PHPMailer Test Subject via mail(), advanced';  $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically  $mail->MsgHTML(file_get_contents('contents.html'));  $mail->AddAttachment('images/phpmailer.gif');      // attachment  $mail->AddAttachment('images/phpmailer_mini.gif'); // attachment  $mail->Send();  echo "Message Sent OK\n";} catch (phpmailerException $e) {  echo $e->errorMessage(); //Pretty error messages from PHPMailer} catch (Exception $e) {  echo $e->getMessage(); //Boring error messages from anything else!}


You can get more info about the error with the method $mail->ErrorInfo. For example:

if(!$mail->send()) {    echo 'Message could not be sent.';    echo 'Mailer Error: ' . $mail->ErrorInfo;} else {    echo 'Message has been sent';}

This is an alternative to the exception model that you need to active with new PHPMailer(true). But if can use exception model, use it as @Phil Rykoff answer.

This comes from the main page of PHPMailer on github https://github.com/PHPMailer/PHPMailer.


Please note!!! You must use the following format when instantiating PHPMailer!

$mail = new PHPMailer(true);

If you don't exceptions are ignored and the only thing you'll get is an echo from the routine! I know this is well after this was created but hopefully it will help someone.