Local Testing & Debugging: wp_mail()

I was recently developing a plugin which, among other things, creates and sends an HTML formatted email using the WordPress function wp_email(). However, I was debugging and testing on a local server which is not setup to send emails.

To get around this I wrote the following simple filter which writes the email to a file on the server which I can open and view with my browser.

function my_wp_mail_filter( $args ) {
    $file_name = '../test_email.html';
    file_put_contents($file_name, '<!DOCTYPE html><html><head><title>Test Email</title><meta charset="UTF-8"></head>');
    file_put_contents($file_name, 'NEW EMAIL from ' . get_bloginfo('name') . '. Created at ' . date("h:i:sa") . '<br><br><br>', FILE_APPEND);
    file_put_contents($file_name, 'Headers: ' . $args['headers'] . '<br><br>', FILE_APPEND);
    file_put_contents($file_name, 'To: ' . $args['to'] . '<br>', FILE_APPEND);
    file_put_contents($file_name, 'Subject: ' . $args['subject'] . '<br>', FILE_APPEND);
    file_put_contents($file_name, $args['message'] . '<br>', FILE_APPEND);
    return false;
} add_filter( 'wp_mail', 'my_wp_mail_filter' );

This filter code goes into the functions.php file of your theme. So now, each time I revise the output HTML email format and content, I can refresh my browser and see the results straightaway.

Leave a Reply

Your email address will not be published.