Clean Up Email Recipient Lists Before Sending
Removes duplicate, malformed and placeholder addresses (such as example.com or .test domains) from email recipient lists, so one bad address does not make the whole email fail.
Opens WPIDE on
Code
$wpide_reserved_domains = array( 'example.com', 'example.org', 'example.net', 'test', 'invalid', 'localhost', 'local' );
add_filter( 'wp_mail', function ( $atts ) use ( $wpide_reserved_domains ) {
$list = is_array( $atts['to'] ) ? $atts['to'] : explode( ',', (string) $atts['to'] );
$clean = array();
foreach ( $list as $recipient ) {
$recipient = trim( (string) $recipient );
$email = strtolower( preg_match( '/<([^>]+)>/', $recipient, $m ) ? trim( $m[1] ) : $recipient );
$domain = (string) substr( strrchr( $email, '@' ), 1 );
$tld = substr( strrchr( '.' . $domain, '.' ), 1 );
if ( ! is_email( $email ) || isset( $clean[ $email ] ) || in_array( $domain, $wpide_reserved_domains, true ) || in_array( $tld, $wpide_reserved_domains, true ) ) {
continue;
}
$clean[ $email ] = $recipient;
}
$atts['to'] = array_values( $clean );
return $atts;
}, 6 );
Notes
Only the To list is cleaned; edit the reserved domains at the top if you really send to any of them.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.