Log WordPress outgoing mails for debugging

May be you are working in a server or in local machine, you may have situations where you want to track if mail is sending as you want. I find it very useful in my local server, because I don’t have any MTP installed in my local machine. So I use this following method to track the outgoing mails.

Utility function for logging:

/**
 * Logs error to file
 * 
 * @uses `error_log` function to log on file
 * 
 * @param string $error message of the error
 * @param string $type type of the error message
 */
function log_error( $error, $type = 'error' ) {
    $path = dirname( __FILE__ ) . '/log.txt';
    $msg = sprintf( "[%s][%s] %s\n", date( 'd.m.Y h:i:s' ), $type, $error );
    error_log( $msg, 3, $path );
}

This function is a helper function that takes any data as input and log the data/error in a text file “log.txt” in the current directory.

Main logger function:

/**
 * Log the mail to text file
 * 
 * @uses `wp_mail` filter
 * @param array $mail
 */
function wedevs_mail_log( $mail ) {

    $message = "to: {$mail['to']} \nsub: {$mail['subject']}, \nmsg:{$mail['message']}";
    log_error( 'mail', $message );

    return $mail;
}

add_filter( 'wp_mail', 'wedevs_mail_log', 10 );

This function adds a filter in the `wp_mail` filter and logs the mail through our logging utility function in the log.txt file. Quite handy, isn’t it?

One thought on “Log WordPress outgoing mails for debugging

  1. I downloaded your wp user frontend plugin yesterday. I was excited because I have been looking for a plugin like this for a while or rather something like this. I have even been to sites that says hire me and got no response, so I want to tell you first for building it and second I’m having problems.
    I don’t know what it means “Edit” page put url in admin option of plugin, third when you try to link to a word in a post the add link button is not working, and this plugin would be much better if the user can preview its work before submitting. I have been using this plugin on my sample site before I go live with it. I can’t use it or tell anyone about it with out the fixes. Its a cool plugin, aim a little towards the buddypress feel without the social. I have guess post sites.

    Thanks.

Leave a Reply