Halloween Sale 15% off Ends in See the plans
PHP

Keep the From Address on Your Own Domain

When a plugin sends email "from" a visitor's or a free webmail address, switches the From to your own domain and keeps the original address as Reply-To, so emails pass SPF and DMARC checks.

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

Code

$wpide_aligned_from = ''; // Address on your domain; empty = wordpress@yourdomain.

add_action( 'phpmailer_init', function ( $phpmailer ) use ( $wpide_aligned_from ) {
    $site   = preg_replace( '/^www\./', '', (string) wp_parse_url( home_url(), PHP_URL_HOST ) );
    $domain = strtolower( (string) substr( strrchr( (string) $phpmailer->From, '@' ), 1 ) );

    if ( '' === $site || $domain === $site || ( strlen( $domain ) > strlen( $site ) && substr( $domain, -strlen( '.' . $site ) ) === '.' . $site ) ) {
        return;
    }

    $original = $phpmailer->From;
    $name     = $phpmailer->FromName;
    $from     = is_email( $wpide_aligned_from ) ? $wpide_aligned_from : 'wordpress@' . $site;

    if ( ! $phpmailer->getReplyToAddresses() && is_email( $original ) ) {
        $phpmailer->addReplyTo( $original, $name );
    }

    $phpmailer->setFrom( $from, $name, false );
}, 999 );

Notes

Set the address to use at the top, or leave it empty to use wordpress@ your domain.

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.