WordPress Mail Debugging

Sometimes you just want to see what emails are sent or what they contain, without actually having them sent.

Cases where this might be desirable include …

  • Working on a development site and you want to avoid that the site sends real emails.
  • Tests during plugin development to see if your plugin sends the right emails.
  • Validating a site to check for undesired emails being sent by plugins.

WordPress allows you to define the wp_mail() function which would be used instead of the default implementation.

The wp_mail() function is one of those pluggable functions that can be replaced via plugins, defined in the site’s wp-config.php or a theme’s functions.php.

This is an example wp_mail() override you can place into your site’s wp-config.php:, replace the line define('WP_DEBUG', false); with the code below:

https://gist.github.com/itthinx/2425c4ebb2ca6a23ff48c0cd53e73fed


// An example wp_mail() override that you can place in your site's wp-config.php

define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );

function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
	$output = sprintf(
		"\n\n" .
		"---------- Caught email ---------- \n\n" .
		"To: %s\n\n" .
		"Subject: %s\n\n" .
		"Message: %s\n\n" .
		"Headers: %s\n\n" .
		"Attachments: %s\n\n" .
		"---------------------------------- \n\n" .
		"\n\n",
		$to,
		$subject,
		$message,
		json_encode( $headers ),
		json_encode( $attachments )
	);
	error_log( $output );
	return true;
}

With this override in place, you will have your site’s emails reflected in its debug.log instead of having them sent. To make sure that debugging is enabled, we have included the appropriate definitions of the debug constants involved in the example: WP_DEBUG set as true to enable debugging, WP_DEBUG_LOG set as true to enable logging and WP_DEBUG_DISPLAY set as false to avoid cluttering the site’s pages with debug messages.

If you want to have detailed control over how, when and which emails are sent, please have a look at our Itthinx Mail Queue plugin.

Remember to remove the override once things have been tested and you are ready for production!


Comments

Leave a Reply

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

Share