Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.