WordPress Email Error Handling

  add_action( 'wp_mail_failed', 'onMailError', 10, 1 );
function onMailError( $wp_error ) {
    echo "<pre>";
    print_r($wp_error);
    echo "</pre>";
} 

Have you ever had to debug WordPress email problems, like mail not being sent, without any apparent reason? The wp_mail function is usually used to send emails from within WordPress code. This is a pluggable function and, thus, resides in wp-includes/pluggable.php.

Debugging wp_mail in WordPress

Its default behavior prevents it from returning anything but false when sending fails for one reason or another. And that often times poses a problem when trying to debug wp_mail issues.


Debugging wp_mail() can be a lot easier with this simple method: wp_mail_failed . It will display a more helpful error message (the original phpmailer error) than WordPress will by default. Just add this function to display the real wp_mail() error. But only use this for debugging.

WordPress relies on the PHPMailer class to send email through PHP’s mail function.

Since PHP’s mail function returns very little information after execution (only TRUE or FALSE), I suggest temporarily stripping down your mv_optin_mail function to a minimum in order to see if the wp_mail functions works.

Example:

$mailResult = false;
$mailResult = wp_mail( '[email protected]', 'test if mail works', 'hurray' );
echo $mailResult;

Since you’ve tested PHP’s mail function already, the mail should arrive.

If it does not, the problem lies in the other statements of your function or in the PHPMailer class.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.