Email PHP Beginner

Block All Outgoing Email on Staging

Stop non-production sites sending any email at all, while logging what would have been sent.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 14 lines
add_filter( 'pre_wp_mail', function ( $return, array $atts ) {
	if ( 'production' === wp_get_environment_type() ) {
		return $return;
	}

	error_log( sprintf(
		'[email blocked on %s] To: %s | Subject: %s',
		wp_get_environment_type(),
		is_array( $atts['to'] ) ? implode( ', ', $atts['to'] ) : $atts['to'],
		$atts['subject']
	) );

	return true; // Pretend it was sent so nothing reports an error.
}, 10, 2 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

If you don’t need to see emails on a staging or development site, the safest option is to send none at all. This snippet blocks them and writes a line to the error log instead.

How it works

Since WordPress 5.7, pre_wp_mail runs before any email is built. Returning anything other than null skips sending. The snippet returns true, so plugins think the email went out and don’t show errors.

Things to watch

  • Set WP_ENVIRONMENT_TYPE to staging, development or local in wp-config.php. On production nothing changes.
  • Only email sent with wp_mail() is blocked.
  • To read the emails instead, use “Send All Email to One Address on Staging”.

How to test it

On staging, reset a password. No email should arrive, and the error log should show an “[email blocked on staging]” line.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only