[php] How can I catch an error caused by mail()?

Does anyone know how can I catch a mail error (error is displayed while sending email and the error is caused by the mailserver down) in php?

Error that was caused by emailserver down is below:

<!--2010-02-24T14:26:43+11:00 NOTICE (5): Unexpected Error: mail() [<a href='function.mail'>function.mail</a>]: Failed to connect to mailserver at "ip " port portip, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set() (# 2).
2010-02-24 14:26:43
Username: admin
Error in line 439 of file D:\test.php
Script: /customer.php
[Global Error Handler]
-->

This question is related to php email

The answer is


also using http://php.net/error_get_last will not help you out, because mail() does not emmit its errors into this function.

Only way seems to be using a proper mailer, like already suggested above.


According to http://php.net/manual/en/function.error-get-last.php, use:

print_r(error_get_last());

Which will return an array of the last error generated. You can access the [message] element to display the error.


PHPMailer handles errors nicely, also a good script to use for sending mail via SMTP...

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

You could use the PEAR Mail classes and methods, which allows you to check for errors via:

if (PEAR::isError($mail)) {
    echo("<p>" . $mail->getMessage() . "</p>");
} else {
    echo("<p>Message successfully sent!</p>");
}

You can find an example here.