Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 11 min read

Fix WordPress Emails Not Sending

When WordPress emails are not sending, the site rarely tells you why. wp_mail() returns a boolean, PHP hands the message to whatever local mail binary happens to exist, and the reason for the failure disappears somewhere

When WordPress emails are not sending, the site rarely tells you why. wp_mail() returns a boolean, PHP hands the message to whatever local mail binary happens to exist, and the reason for the failure disappears somewhere between the two. This walkthrough compares the three realistic ways to get mail out of WordPress, then implements the one that leaves a trail: an authenticated SMTP relay, a failure logger that survives plugin deactivation, and DNS records that prove the message is allowed to claim your domain.

You need shell access with WP-CLI, an SMTP relay account, and the ability to edit DNS records for the sending domain. The logging and bisecting steps work without the last two.

Why a true return from wp_mail() proves almost nothing about delivery

wp_mail() lives in wp-includes/pluggable.php, which means any plugin can replace it before core loads. The core version builds a PHPMailer instance and, unless something changes the mailer, leaves $phpmailer->Mailer set to mail. That hands the message to PHP's mail(), which hands it to a local sendmail-compatible binary.

Two things follow. On a container or a host with no MTA, the call fails and you get false, but only if you are looking. On a host with a permissive MTA, the call returns true and the message is still dropped by the recipient because it carried no authentication, no aligned SPF record and a From address the receiving server distrusts. The wp_mail() reference is explicit that the return value means "accepted by the mailer", not "delivered".

Three routes out of WordPress, and the one worth wiring up

  • Local MTA / PHP mail(). Zero configuration, and occasionally fine on a managed shared host that monitors its own queue. It has no authentication, no TLS, no delivery feedback, and no way to tell you why a message vanished. Fits only when the host provides and monitors the MTA and you control the domain's DNS.
  • Authenticated SMTP relay through phpmailer_init. You keep core's wp_mail() API, so every plugin, including WooCommerce order emails, keeps working unchanged. The relay returns real SMTP codes (535 authentication failed, 550 sender rejected, TLS handshake errors) which the failure logger can capture. Fits almost every site that needs mail to arrive.
  • Transactional HTTP API. Replaces SMTP with a provider's REST endpoint, usually via a plugin that hooks pre_wp_mail. Best deliverability and webhook-based bounce handling, at the cost of a provider SDK, per-message pricing and a hard dependency you carry through every migration. Fits high-volume stores and sites where a missing password reset has a direct financial cost.

The rest of this article implements the middle option, because it fixes delivery without changing the API your plugins already call, and it produces error strings you can act on.

Log wp_mail failures before you change a single setting

Change the configuration first and you destroy the evidence: the exception message, the recipient and the timestamp are exactly what tells you whether the problem is authentication, DNS or a plugin. Install this as a must-use plugin so it loads before regular plugins and stays active while you deactivate everything during conflict testing.

<?php
/**
 * Plugin Name: WP Tuts Hub Mail Logger
 * Description: Records wp_mail() failures to a log file and shows the last one to administrators.
 */

defined( 'ABSPATH' ) || exit;

define( 'WP_TUTS_HUB_MAIL_LOG', 'wp-tuts-hub-mail-errors.log' );

function wp_tuts_hub_mail_log_path() {
    return WP_CONTENT_DIR . '/' . WP_TUTS_HUB_MAIL_LOG;
}

add_action( 'wp_mail_failed', 'wp_tuts_hub_log_mail_failure' );

function wp_tuts_hub_log_mail_failure( $error ) {
    if ( ! is_wp_error( $error ) ) {
        return;
    }

    $data  = (array) $error->get_error_data();
    $entry = sprintf(
        "[%s] %s | to: %s | subject: %s\n",
        gmdate( 'c' ),
        $error->get_error_message(),
        isset( $data['to'] ) ? implode( ', ', (array) $data['to'] ) : 'unknown',
        isset( $data['subject'] ) ? $data['subject'] : 'unknown'
    );

    error_log( $entry, 3, wp_tuts_hub_mail_log_path() );
    update_option( 'wp_tuts_hub_last_mail_error', $entry, false );
}

add_action( 'admin_notices', 'wp_tuts_hub_mail_error_notice' );

function wp_tuts_hub_mail_error_notice() {
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }

    $last = get_option( 'wp_tuts_hub_last_mail_error' );

    if ( ! $last ) {
        return;
    }

    printf(
        '<div class="notice notice-error"><p><strong>%s</strong> %s</p></div>',
        esc_html__( 'Mail delivery error (wp_mail_failed):', 'wp-tuts-hub' ),
        esc_html( $last )
    );
}

The wp_mail_failed action fires with a WP_Error whose data array carries to, subject, headers, attachments and phpmailer_exception_code. Writing that to wp-content/wp-tuts-hub-mail-errors.log keeps the record next to the site instead of in a PHP error log you may not have access to. The dashboard notice exists so a non-technical administrator can report the exact error instead of saying "email is broken".

Two housekeeping notes: the log file sits inside wp-content, so exclude it from any public backup or sync, and rotate it by deleting it once you have read it.

Reproduce the failure from the command line with WP-CLI

Triggering mail through the browser (a password reset, a WooCommerce order) is slow and hides the return value. WP-CLI's eval command gives you the boolean and the log entry in one repeatable step.

# 1. Does wp_mail() reach PHPMailer at all? Prints true or false.
wp eval 'var_dump( wp_mail( "[email protected]", "WP Tuts Hub test", "Plain text body" ) );'

# 2. Force a failure PHPMailer cannot accept, so the logger has something to record.
wp eval 'var_dump( wp_mail( "not-an-email", "WP Tuts Hub failure test", "Body" ) );'

# 3. Read what the logger captured.
wp eval 'echo file_get_contents( WP_CONTENT_DIR . "/wp-tuts-hub-mail-errors.log" );'

The three commands on a site with no local mail server, and what the logger recorded (test site: WordPress 7.1.3, PHP 8.2):

$ wp eval 'var_dump( wp_mail( "[email protected]", "WP Tuts Hub test", "Plain text body" ) );'
sh: 1: /usr/sbin/sendmail: not found
bool(false)

$ wp eval 'var_dump( wp_mail( "not-an-email", "WP Tuts Hub failure test", "Body" ) );'
bool(false)

$ wp eval 'echo file_get_contents( WP_CONTENT_DIR . "/wp-tuts-hub-mail-errors.log" );'
[2026-11-11T13:38:15+00:00] Could not instantiate mail function. | to: [email protected] | subject: WP Tuts Hub test
[2026-11-11T13:38:15+00:00] You must provide at least one recipient email address. | to: not-an-email | subject: WP Tuts Hub failure test

The second command deliberately passes an address PHPMailer rejects, which guarantees a wp_mail_failed event even on a host where real mail would otherwise be accepted. The log line records the exception message, the recipient and the subject, so you can tell a rejected address apart from a refused connection.

The same failure is visible without a terminal: the mu-plugin prints the last recorded error as a dashboard notice for anyone with manage_options.

The dashboard notice the mu-plugin shows after a failed wp_mail() call (test site: WordPress 7.1.3, PHP 8.2)

Isolate the plugin that is swallowing your mail

If the logger stays silent while mail still disappears, the message is being stopped before PHPMailer runs. The usual culprit is the pre_wp_mail filter: return anything other than null from it and wp_mail() short-circuits, no exception is thrown, and no failure hook fires. A plugin that declares its own wp_mail() has the same effect.

# What is actually active?
wp plugin list --status=active --field=name

# Baseline with every regular plugin off. The mu-plugin logger stays loaded.
wp plugin deactivate --all
wp eval 'var_dump( wp_mail( "[email protected]", "Baseline", "Body" ) );'

# Switch plugins back on in halves and re-run the same test.
wp plugin activate woocommerce
wp eval 'var_dump( wp_mail( "[email protected]", "After WooCommerce", "Body" ) );'

# Is anything short-circuiting wp_mail() before PHPMailer runs?
wp eval 'global $wp_filter; var_dump( isset( $wp_filter["pre_wp_mail"] ) );'

Bisecting in halves matters more than it sounds: deactivating everything proves the problem is plugin-related, but reactivating one at a time on a site with thirty plugins wastes an afternoon. The $wp_filter check at the end tells you whether anything is registered on pre_wp_mail at all: if the output is true, read those callbacks before you touch SMTP settings.

Point PHPMailer at an authenticated relay with phpmailer_init

Credentials belong in wp-config.php or the environment, never in the database where a plugin export or a staging clone will copy them. Define the constants above the "That's all, stop editing" line, because anything below wp-settings.php is loaded too late to be used.

// wp-config.php, above the "stop editing" line.
define( 'WP_TUTS_SMTP_HOST', 'smtp.example-relay.com' );
define( 'WP_TUTS_SMTP_PORT', 587 );
define( 'WP_TUTS_SMTP_USER', getenv( 'SMTP_USER' ) ?: '' );
define( 'WP_TUTS_SMTP_PASS', getenv( 'SMTP_PASS' ) ?: '' );
define( 'WP_TUTS_SMTP_FROM', '[email protected]' );

Then append the mailer configuration to the same mu-plugin. The phpmailer_init action receives the live PHPMailer object just before send(), which is the last safe point to change the transport.

add_action( 'phpmailer_init', 'wp_tuts_hub_configure_smtp' );

function wp_tuts_hub_configure_smtp( $phpmailer ) {
    if ( ! defined( 'WP_TUTS_SMTP_HOST' ) || ! WP_TUTS_SMTP_HOST ) {
        return;
    }

    $phpmailer->isSMTP();
    $phpmailer->Host        = WP_TUTS_SMTP_HOST;
    $phpmailer->Port        = (int) WP_TUTS_SMTP_PORT;
    $phpmailer->SMTPAuth    = true;
    $phpmailer->Username    = WP_TUTS_SMTP_USER;
    $phpmailer->Password    = WP_TUTS_SMTP_PASS;
    $phpmailer->SMTPSecure  = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
    $phpmailer->SMTPAutoTLS = true;

    // The envelope sender decides which domain SPF is checked against.
    $phpmailer->Sender = WP_TUTS_SMTP_FROM;

    // $auto = false: do not throw if a plugin already set a From address.
    $phpmailer->setFrom( WP_TUTS_SMTP_FROM, get_bloginfo( 'name' ), false );
}

Each line earns its place. isSMTP() overrides the default mail transport. ENCRYPTION_STARTTLS on port 587 upgrades a plain connection; use ENCRYPTION_SMTPS on port 465 instead, not both. Sender sets the envelope sender, which is the address SPF is checked against: leave it unset and the relay may use its own bounce domain, breaking DMARC alignment. Passing false as the third argument to setFrom() stops PHPMailer throwing when a plugin has already set a From header, which is common with contact form plugins.

Never set the From address to a free mailbox you do not own, such as a Gmail address: Gmail publishes p=reject in its DMARC record, so a relay sending on its behalf is rejected outright. Verify the new path with wp eval 'var_dump( wp_mail( "[email protected]", "SMTP relay test", "Body" ) );' and read the log if it returns false.

Check SPF, DKIM and DMARC against the domain you actually send from

A relay accepting the message is only half the job; the receiving server still scores it. SPF authorises the relay's IP addresses for the envelope domain, DKIM signs the message with a key published under your domain, and DMARC requires at least one of them to align with the From header. Query the records from the server that sends the mail, not from your laptop.

# SPF: is the relay listed as an authorised sender for the envelope domain?
dig +short TXT example.com | tr -d '"' | grep -i "v=spf1"

# DKIM: the selector is provider-specific (Postmark pm, SendGrid s1, Mailgun smtp).
dig +short TXT pm._domainkey.example.com

# DMARC: start at p=none to collect reports, then move to quarantine.
dig +short TXT _dmarc.example.com

Alignment is where most setups fail. If the relay rewrites the envelope sender to its own bounce domain, SPF passes for the relay but no longer aligns with your From domain, so DMARC depends entirely on DKIM being signed with d=example.com. Most providers offer a custom Return-Path CNAME for exactly this reason; configure it so both mechanisms align. Start DMARC at p=none with a reporting address, read the aggregate reports for a week, then tighten to quarantine.

The final proof is a real message: send one to a Gmail account, open "Show original", and look for spf=pass, dkim=pass and dmarc=pass in the Authentication-Results header. A pass there is worth more than any plugin's green tick.

When wp_mail_failed never fires and mail still disappears

  • Something replaced wp_mail(). Confirm the loaded function comes from core with wp eval 'echo ( new ReflectionFunction( "wp_mail" ) )->getFileName();'. If the path is not wp-includes/pluggable.php, a plugin owns the function and none of core's hooks run.
  • Outbound ports are blocked. A log entry reading "SMTP connect() failed" or a timeout means the host blocks 587 and 465. Ask for the ports to be opened, or use the provider's alternative port such as 2525.
  • The message was sent and filtered. A silent logger plus a true return means the relay accepted it. Check the recipient's spam folder and the Authentication-Results header before changing any code.
  • The From address is rejected. A 550 "sender address rejected" is a policy decision at the relay: the domain in WP_TUTS_SMTP_FROM must be verified in the provider's dashboard.
  • Constants defined too late. If WP_TUTS_SMTP_HOST is defined below require_once ABSPATH . 'wp-settings.php';, the guard in the hook returns early and the site silently keeps using PHP mail().

Keep the logger running for the first hundred messages

Mail sent from scheduled events, such as digests and reminders, also depends on WP-Cron running on time. If those emails arrive late or not at all while password resets work, debugging WP-Cron single events is the next place to look.

The obvious follow-up is to make the log two-sided: hook wp_mail_succeeded to write a one-line success record with the recipient and subject, then add a weekly cron event that emails you a count of failures against successes. Two weeks of that data tells you whether a relay or DNS change actually fixed delivery, rather than waiting for a customer to report a password reset that never arrived.

Originally published on WP Tuts Hub.

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.