HOMEBlogWordPressWordPress Email Not Sending: 5 Easy Steps to…

WordPress Email Not Sending: 5 Easy Steps to Debug wp_mail Failures with Error Logging

WordPress Email Not Sending

When wp_mail() fails, WordPress may not show a site owner enough detail to tell whether the cause is WordPress, PHP, or the mail transport. To investigate WordPress Email Not Sending, attach a small logger to the wp_mail_failed hook, write sanitized diagnostics to a private log, and run a controlled test to identify the likely cause.

This hook reports failures during WordPress mail processing; it does not record every downstream delivery problem. In particular, a successful return from wp_mail() does not prove that a message reached the recipient’s inbox. Use staging where possible, keep message contents and credentials out of logs, and prepare these essentials before changing mail settings:

  • PHP 8.0 or newer and a WordPress installation where you can add a must-use plugin.
  • A recent backup and, preferably, a staging site for reproducing failures safely.
  • SSH, SFTP, or hosting control panel access, with permission to create and edit files.
  • A writable log location outside the public web root, or access to a protected server PHP error log.
  • Access to the configured mail transport settings and a test mailbox you can use to receive messages.

Prepare a Safe Debugging Baseline

Start on staging whenever possible. A deliberate mail failure can create repeated alerts, expose a mail configuration mistake, or affect real recipients if a production workflow is used for testing. Take a backup first, and choose a test mailbox rather than a customer address.

Temporarily enable WordPress debugging without displaying PHP errors to visitors. Add or update these definitions in wp-config.php above the line that says /* That's all, stop editing! */. Replace any existing definitions instead of declaring the constants twice.

PHP
define('WP_DEBUG', true);
define('WP_DEBUG_LOG', '/srv/private-logs/wordpress-debug.log');
define('WP_DEBUG_DISPLAY', false);
@ini_set('display_errors', '0');

The example uses a custom log path outside the public web root. Create the directory before testing and ensure the PHP process can write to it; use restrictive ownership and permissions, such as access limited to the site account. The path is server-specific, so substitute a private location that exists on your host. Do not put SMTP passwords, message bodies, or other mail contents in configuration examples or diagnostic notes.

Backup Required
Keep debugging enabled only for the time needed to investigate. If staging is unavailable and you must work on production, schedule a short maintenance window, confirm errors remain hidden from visitors, and arrange to remove or rotate the log immediately after testing.

If you use the standard WordPress debug log instead, setting WP_DEBUG_LOG to true writes to wp-content/debug.log. That directory may be web-accessible on some hosts, so restrict access at the server level or choose a protected path. The next step adds a focused failure logger; this baseline only prepares private, temporary diagnostics.

Trace WordPress Email Not Sending with wp_mail_failed

Create a must-use plugin so the logger loads independently of regular plugin activation. On staging, create wp-content/mu-plugins if needed, then save the following as pnet-mail-failure-logger.php. The callback receives a WP_Error object when WordPress fires wp_mail_failed.

Register the Hook and Sanitize the Log Entry

Set the log path to a location outside the public web root that the PHP process can write to. The code records only a UTC timestamp, error code, and sanitized message; it does not dump the error data, which may contain recipients, subjects, message bodies, headers, or attachment details. If the private file cannot be written, it sends the already-sanitized entry to the server PHP error log without displaying it to visitors.

PHP
<?php
if (!defined('ABSPATH')) {
    exit;
}

if (!defined('PNET_MAIL_FAILURE_LOG_PATH')) {
    define('PNET_MAIL_FAILURE_LOG_PATH', '/srv/private-logs/wp-mail-failures.log');
}

add_action('wp_mail_failed', 'pnet_log_wp_mail_failure', 10, 1);

function pnet_log_wp_mail_failure($error) {
    if (!($error instanceof WP_Error)) {
        return;
    }

    $original_code = $error->get_error_code();
    $entry = array(
        'timestamp_utc' => gmdate('c'),
        'error_code' => sanitize_key((string) $original_code),
        'message' => pnet_redact_mail_error($error->get_error_message($original_code)),
    );

    $line = wp_json_encode($entry, JSON_UNESCAPED_SLASHES);
    if (!is_string($line)) {
        error_log('wp_mail_failed diagnostic could not be encoded.');
        return;
    }

    $directory = dirname(PNET_MAIL_FAILURE_LOG_PATH);
    if (is_dir($directory) && is_writable($directory)) {
        $written = @file_put_contents(
            PNET_MAIL_FAILURE_LOG_PATH,
            $line . PHP_EOL,
            FILE_APPEND | LOCK_EX
        );

        if ($written !== false) {
            @chmod(PNET_MAIL_FAILURE_LOG_PATH, 0600);
            return;
        }
    }

    error_log($line);
}

function pnet_redact_mail_error($message) {
    $message = wp_strip_all_tags((string) $message);
    $message = preg_replace(
        '/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i',
        '[redacted-email]',
        $message
    );
    $message = preg_replace(
        '/\b(password|passwd|token|secret|authorization|api[_ -]?key)\b\s*[:=]\s*[^\s,;]+/i',
        '$1=[redacted]',
        (string) $message
    );

    if (!is_string($message)) {
        return 'Diagnostic message could not be sanitized.';
    }

    return substr($message, 0, 1000);
}

Replace the example path with a real private directory and confirm that both the directory and server error log are protected from public access. The redaction is a safeguard, not a reason to log full error data: inspect the callback and keep the recorded fields limited. See the official wp_mail_failed hook reference for its action details.

WordPress Email Not Sending - Private Log Workflow
Private Log Workflow
Pro Tip
Keep the private directory outside the web root, restrict its permissions, and rotate or remove the diagnostic file when testing is complete. The PHP error-log fallback must also be protected by your host configuration.

Register the Failure Hook and Sanitize Diagnostic Data

The callback should accept only a WP_Error, then read its first error code and corresponding message. Error messages can include server responses or other sensitive values, so sanitize the message before writing it and avoid logging the error data array, headers, or mail content. This example records only a UTC timestamp, a sanitized code, and a redacted message.

PHP
<?php
if (!defined('ABSPATH')) {
    exit;
}

if (!defined('PNET_MAIL_FAILURE_LOG_PATH')) {
    define('PNET_MAIL_FAILURE_LOG_PATH', '/srv/private-logs/wp-mail-failures.log');
}

add_action('wp_mail_failed', 'pnet_log_wp_mail_failure', 10, 1);

function pnet_log_wp_mail_failure($error) {
    if (!($error instanceof WP_Error)) {
        return;
    }

    $code = $error->get_error_code();
    $entry = array(
        'timestamp_utc' => gmdate('c'),
        'error_code' => sanitize_key((string) $code),
        'message' => pnet_redact_mail_error($error->get_error_message($code)),
    );

    $line = wp_json_encode($entry, JSON_UNESCAPED_SLASHES);
    if (!is_string($line)) {
        error_log('wp_mail_failed diagnostic could not be encoded.');
        return;
    }

    $directory = dirname(PNET_MAIL_FAILURE_LOG_PATH);
    if (is_dir($directory) && is_writable($directory)) {
        $written = @file_put_contents(
            PNET_MAIL_FAILURE_LOG_PATH,
            $line . PHP_EOL,
            FILE_APPEND | LOCK_EX
        );
        if ($written !== false) {
            @chmod(PNET_MAIL_FAILURE_LOG_PATH, 0600);
            return;
        }
    }

    error_log($line);
}

function pnet_redact_mail_error($message) {
    $message = wp_strip_all_tags((string) $message);
    $message = preg_replace(
        '/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i',
        '[redacted-email]',
        $message
    );
    $message = preg_replace(
        '/\b(password|passwd|token|secret|authorization|api[_ -]?key)\b\s*[:=]\s*[^\s,;]+/i',
        '$1=[redacted]',
        (string) $message
    );

    if (!is_string($message)) {
        return 'Diagnostic message could not be sanitized.';
    }

    return substr($message, 0, 1000);
}

Change the sample path to an existing directory outside the public web root that the PHP process can write to. The file append uses a lock to reduce collisions, and the permissions are restricted after writing; verify that the server account and host policy support this setup. Redaction is a safeguard, not a guarantee that every server response is safe to retain, so keep the logged fields narrow and protect the fallback PHP error log too. The official wp_mail_failed hook reference describes when WordPress fires this action; it does not indicate whether a message later reaches an inbox.

Reproduce a Controlled Failure and Confirm the Hook Runs

Begin on staging with a normal test using a mailbox you control. Save the following as a temporary PHP file outside the public web root, replace the example recipient, then run it from the WordPress installation directory with wp eval-file /secure/path/pnet-mail-probe.php. This confirms whether the current mail path accepts a message without involving a customer workflow.

A true result means WordPress handed the message to its configured mail path; it is not proof of inbox delivery. Check the mailbox and, if necessary, the provider delivery records. A false result is a useful signal, but not every short-circuited mail attempt fires wp_mail_failed; the hook reports failures during WordPress mail processing, not later bounces or spam filtering.

To verify the logger itself, use staging only: temporarily enter incorrect test SMTP credentials or make the test transport unavailable, then run the same probe once. Restore the valid settings immediately afterward. Confirm that exactly one new, timestamped entry appears in the private log and contains neither the test message nor credentials. If the call returns false but no entry appears, use the Common Errors checks to investigate the hook, plugin load, and log permissions.

Read the Log and Isolate the Mail Transport

Open the private log and locate the entry matching your test. A redacted example might look like {"timestamp_utc":"2025-03-08T14:22:10+00:00","error_code":"smtp_connect_failed","message":"Connection timed out while connecting to [redacted-host]"}. The UTC timestamp lets you correlate the event with server records, the error code identifies the failure category, and the message offers a clue without retaining message content or credentials.

WordPress Email Not Sending - Redacted Log Triage
Redacted Log Triage

Read the message as a direction for investigation, not a complete diagnosis. Authentication rejection points to credentials, authentication method, or account restrictions. A connection timeout suggests an unreachable host, blocked outbound port, or unavailable service. DNS or hostname errors call for checking the configured server name and name resolution. TLS or certificate errors suggest mismatched encryption settings, an expired certificate, or a trust-chain problem. Rate-limit responses indicate provider quotas or sending policy; sender-address rejection may mean the From address is not authorized or is malformed.

Check which transport is active, then compare the entry timestamp with that transport’s SMTP, hosting, or PHP mail logs. Inspect relevant configuration without copying secrets into notes, and change one setting at a time. A WordPress processing error is distinct from a later provider rejection, bounce, or spam-folder placement.

For Developers
The wp_mail_failed hook reports a failure during WordPress mail processing. It is not a delivery receipt, and a successful return from wp_mail() does not prove inbox delivery.

Fix the Root Cause and Retest the Mail Path

Use the logged error signature to choose one setting to investigate, rather than changing several parts of the mail configuration at once. Keep tests on staging and use a mailbox you control. Do not copy passwords, application credentials, or other secrets into diagnostic notes or logs.

For authentication rejections, verify the SMTP username, password or application credential, and configured authentication method. Check whether the provider requires an app-specific credential, has blocked the account, or imposes restrictions on the sender. Make corrections through the secure settings interface; never put credentials in test scripts or log output.

For connection timeouts, confirm the SMTP hostname and port, then ask the hosting provider or server administrator whether outbound connections to that destination are allowed. For TLS or certificate errors, verify that the encryption mode matches the selected port and that the server certificate is valid and trusted. Avoid disabling certificate verification as a workaround.

If the error concerns the sender address or policy, configure an authorized From address and check the domain’s mail authentication records and provider sending limits. After each change, send one fresh staging test, note its UTC timestamp, and compare the result with the private log and transport records. This makes it easier to identify which correction helped and to reverse an unsuccessful change.

A successful wp_mail() return indicates that WordPress handed the message to its mail path; it does not confirm inbox delivery. When receipt matters, verify the provider’s delivery or bounce records as well as the test mailbox. Once the failure is resolved, continue to the cleanup steps so temporary diagnostics do not remain active longer than necessary.

You might also like:

Gutenberg Query Loop: Add Custom Filtering Arguments in 5 Easy Steps

Gutenberg Query Loop lacks custom filters? Add tailored query arguments in WordPress to control results. Read the step-by-step guide.

Read more →

Common Errors

When the logger and mail test disagree, check the failure path and logging setup separately. Avoid repeatedly sending messages while diagnosing; a single controlled staging test with a known timestamp is easier to trace.

The Failure Hook Does Not Fire

A mail plugin or custom integration may replace or short-circuit the expected mail path, and some failures occur before WordPress fires wp_mail_failed. Confirm which mail plugin and transport are active, then repeat the test using the same method as the failing workflow. Do not treat an absent hook entry as proof that delivery succeeded.

No Log Entry or an Unhelpful Message

Verify the file is in wp-content/mu-plugins, that the MU-plugin filename ends in .php, and that the callback is registered. Check PHP syntax and the server error log for load-time errors. Confirm the private directory exists and is writable by the PHP process. If the entry is present but its message is blank or generic, retain the error code, make sure sanitization is not removing useful text, and compare the timestamp with the active transport logs.

The Logger Cannot Write

Check the configured path, directory ownership, permissions, and hosting restrictions. The PHP process needs write access; avoid solving this by making the log directory publicly accessible. If the logger uses a PHP error-log fallback, ask the host where that log is stored and verify its access controls.

WordPress Reports Success but No Message Arrives

A true result from wp_mail() is not an inbox receipt. The provider may reject the message later, a bounce may be generated, or spam filtering may move it. Check provider delivery and bounce records, then compare their timestamps with the test.

The Log Contains Private Data

Stop the logger immediately, restrict access to or remove the exposed file, and rotate any credentials that may have been recorded. Replace the logger with the redacted version, then verify a new test entry contains only the intended diagnostic fields.

You might also like:

Unbiased Divi Builder Review (2026): Is It the Ultimate WordPress Tool?

Choosing the right page builder can make or break your workflow as a WordPress developer. In this comprehensive Divi Builder...

Read more →

Disable Temporary Diagnostics and Verify Recovery

After the transport issue is resolved, restore the debugging configuration you had before testing. Turn off temporary WP_DEBUG settings if they were not already enabled, and keep WP_DEBUG_DISPLAY disabled on a live site. Restore the previous values rather than assuming every site should use the same settings.

Remove pnet-mail-failure-logger.php from wp-content/mu-plugins if the logger was only for this investigation. If you retain it, document its purpose, keep the logged fields privacy-reviewed, and set a clear retention and rotation policy. A diagnostic file should not become a permanent record of mail activity.

  • Delete or securely archive temporary logs according to your data-handling policy.
  • Confirm the log and its directory are not reachable over HTTP, and restrict access to any retained copy.
  • Remove temporary test scripts and restore any deliberately changed staging credentials or transport settings.

Run one final test through the real site workflow, such as the form or notification that originally failed. Check the configured transport result and compare the test time with provider delivery or bounce evidence when inbox receipt matters. A successful wp_mail() return alone does not confirm delivery.

A private, redacted log helps distinguish a WordPress processing failure from a transport problem, while a controlled retest confirms whether the correction worked. With temporary diagnostics removed and delivery evidence checked, the workflow for WordPress Email Not Sending is complete.

Conclusion

To diagnose mail failures safely, capture the wp_mail_failed action with a small, pnet_-prefixed callback. Record only a UTC timestamp, error code, and sanitized message in a private log; never dump the full WP_Error data, which may include recipients, headers, or message content. Match the entry to your active mail transport logs, then use a controlled staging test and change one setting at a time. This turns a vague failure into useful evidence for investigating authentication, connectivity, TLS, sender policy, or another transport issue.

Keep the hook’s limits in mind: it reports failures during WordPress mail processing, not every downstream rejection or delivery problem. A successful return from wp_mail() does not confirm that a message reached an inbox, so check the provider’s delivery or bounce records when receipt matters. Once the issue is resolved, restore temporary debugging settings, remove or securely rotate diagnostic logs, and delete the temporary logger unless you have reviewed its privacy and retention behavior. These steps provide a practical, safer way to resolve WordPress Email Not Sending without exposing sensitive mail data or leaving diagnostics behind.

Abhik

🚀 Full Stack WP Dev | ☕ Coffee Enthusiast | 🏍️ Biker | 📈 Trader
Hi, I’m Abhik. I’ve been coding since 2007, a journey that began when I outgrew Blogger and migrated to a robust self-hosted stack. That transition introduced me to WordPress, and I’ve been building professional solutions ever since.

Leave a comment