Email PHP Advanced

Log Every Email WordPress Sends

Keep a 30-day log of every email WordPress tries to send, with the recipient, subject, result and error message, in a small database table.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 57 lines
function nahnu_mail_log_table(): string {
	global $wpdb;
	return $wpdb->prefix . 'nahnu_mail_log';
}

// Create the table once.
add_action( 'admin_init', function (): void {
	if ( '1' === get_option( 'nahnu_mail_log_db' ) ) {
		return;
	}
	global $wpdb;
	require_once ABSPATH . 'wp-admin/includes/upgrade.php';
	dbDelta( 'CREATE TABLE ' . nahnu_mail_log_table() . " (
		id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
		recipient text NOT NULL,
		subject varchar(255) NOT NULL DEFAULT '',
		status varchar(10) NOT NULL DEFAULT 'sent',
		error text NULL,
		sent_at datetime NOT NULL,
		PRIMARY KEY  (id),
		KEY sent_at (sent_at)
	) {$wpdb->get_charset_collate()};" );
	update_option( 'nahnu_mail_log_db', '1', false );
} );

function nahnu_write_mail_log( array $mail, string $status, string $error = '' ): void {
	global $wpdb;
	$to = is_array( $mail['to'] ?? '' ) ? implode( ', ', $mail['to'] ) : (string) ( $mail['to'] ?? '' );
	$wpdb->insert( nahnu_mail_log_table(), [
		'recipient' => sanitize_text_field( $to ),
		'subject'   => mb_substr( sanitize_text_field( (string) ( $mail['subject'] ?? '' ) ), 0, 255 ),
		'status'    => $status,
		'error'     => $error,
		'sent_at'   => current_time( 'mysql', true ),
	] );
}

// Sent successfully (WordPress handed it to the mail server).
add_action( 'wp_mail_succeeded', function ( array $mail ): void {
	nahnu_write_mail_log( $mail, 'sent' );
} );

// Failed: the error carries the original message details.
add_action( 'wp_mail_failed', function ( WP_Error $error ): void {
	nahnu_write_mail_log( (array) $error->get_error_data(), 'failed', $error->get_error_message() );
} );

// Keep 30 days.
add_action( 'init', function (): void {
	if ( ! wp_next_scheduled( 'nahnu_mail_log_cleanup' ) ) {
		wp_schedule_event( time(), 'daily', 'nahnu_mail_log_cleanup' );
	}
} );
add_action( 'nahnu_mail_log_cleanup', function (): void {
	global $wpdb;
	$wpdb->query( $wpdb->prepare( 'DELETE FROM ' . nahnu_mail_log_table() . ' WHERE sent_at < %s', gmdate( 'Y-m-d H:i:s', time() - 30 * DAY_IN_SECONDS ) ) );
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

When a customer says they never got an email, the first question is whether WordPress even tried to send it. This snippet logs every email that goes through wp_mail(), with the recipient, subject, whether it was handed off successfully and the error message when it wasn’t.

How it works

WordPress fires wp_mail_succeeded after PHPMailer accepts a message, and wp_mail_failed when sending throws an error. Both pass the original message details: the success hook passes them directly, and the failure hook stores them as the error’s data. The snippet writes one row per email to its own table.

The previous version passed details between hooks through a transient, which mixed up recipients when two emails were sent at the same time, and it ran its table check on every page load. This version reads the details from the hooks themselves and creates the table only once.

What “sent” means

“Sent” means WordPress handed the email to your mail server or SMTP service without an error. It doesn’t prove the email reached the inbox. If emails show as sent but never arrive, check your SMTP service’s own logs and your domain’s SPF, DKIM and DMARC records.

Reading the log

Run wp db query "SELECT sent_at, status, recipient, subject, error FROM wp_nahnu_mail_log ORDER BY id DESC LIMIT 50", swapping wp_ for your table prefix, or open the table in your host’s database tool.

Privacy

Email addresses are personal data. The log keeps 30 days and doesn’t store message bodies. Change 30 in the cleanup task if you need a shorter or longer history, and mention the log in your privacy policy.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only