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

0 votes
asked Feb 24, 2010 by jin-yong

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]

5 Answers

0 votes
answered Jan 24, 2010 by mike-trpcic

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.

0 votes
answered Jan 24, 2010 by fire

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!";
0 votes
answered Feb 24, 2010 by deceze

This is about the best you can do:

if (!mail(...)) {
   // Reschedule for later try or panic appropriately!

mail() returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.

It is important to note that just because the mail was accepted for delivery, it does NOT mean the mail will actually reach the intended destination.

If you need to suppress warnings, you can use:

if (!@mail(...))

Be careful though about using the @ operator without appropriate checks as to whether something succeed or not.

If mail() errors are not suppressible (weird, but can't test it right now), you could:

a) turn off errors temporarily:

$errLevel = error_reporting(E_ALL ^ E_NOTICE);  // suppress NOTICEs
error_reporting($errLevel);  // restore old error levels

b) use a different mailer, as suggested by fire and Mike.

If mail() turns out to be too flaky and inflexible, I'd look into b). Turning off errors is making debugging harder and is generally ungood.

0 votes
answered Jan 16, 2013 by staabm

also using 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.

0 votes
answered Jan 20, 2015 by dairy-window

According to, use:


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

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter