How to catch mail() error?

The manual says that mail() returns a boolean. I have tried both of the following ways to catch an error:

$sent = mail($to, "Comment email from web site", $message, $headers);
if($sent){
	$user_message = "Your email has been sent.";
}else{
	$user_message = "There was a problem sending your email.";
}

if(mail($to, "Comment email from web site", $message, $headers)){
	$user_message = "Your email has been sent.";
}else{
	$user_message = "There was a problem sending your email.";
}

I an testing with obviously bad email recipients in the $to field and get the following error message:

Warning: mail() [function.mail]: SMTP server response: 550 Invalid recipient: <->

But the $user_message still show “Your email has been sent.”

Any ideas?

The return value from $mail refers only to whether or not your server’s mailing system accepted the message for delivery, and does not and can not in any way know whether or not you are providing valid arguments. For example, the return value would be false if sendmail failed to load (e.g. if it wasn’t installed properly), but would return true if sendmail loaded properly but the recipient address doesn’t exist.

I realize that what I really need to do is check the recipient email address but if it sends that warning back before rendering the page, can’t I catch that?

Actually, it looks like [fphp]set_error_handler[/fphp] would work for you. Somehow I’d had it in my head that it could only catch user-defined errors, but actually it can catch any run-time error, including the warning you’re getting!