Stop WordPress From Sending Emails (And Log Them Too!)

While doing some development work recently, I wanted to make sure that I disabled all email sending in my test site so that no users imported would get any weird emails.

To do this I had ChatGPT whip me up a quick plugin, and after cleaning it up here it is to share with the world:

<?php
/**
 * Plugin Name: Restrict and Log Emails
 * Description: Blocks emails for users who do not have 'manage_options' and logs all email attempts.
 * Version: 1.2
 * Author: Emrikol
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit; // Prevent direct access.
}

/**
 * Creates the 'email_log' table in the WordPress database upon plugin activation.
 *
 * @return void
 */
function rel_add_admin_menu(): void {
	// Ensure the admin menu is added.
	if ( function_exists( 'add_submenu_page' ) ) {
		add_submenu_page(
			'tools.php',
			'Email Log',
			'Email Log',
			'manage_options',
			'email-log',
			'rel_email_log_page'
		);
	}
}
add_action( 'admin_menu', 'rel_add_admin_menu' );

/**
 * Displays the Email Log page in the WordPress admin area.
 *
 * @return void
 */
function rel_email_log_page(): void {
	global $wpdb;
	$table_name = $wpdb->prefix . 'email_log';
	$logs       = $wpdb->get_results( "SELECT * FROM $table_name ORDER BY sent_at DESC LIMIT 50" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared

	echo '<div class="wrap">';
	echo '<h1>Email Log</h1>';
	echo '<table class="widefat fixed" cellspacing="0">';
	echo '<thead><tr><th>ID</th><th>Email</th><th>Subject</th><th>Status</th><th>Sent At</th></tr></thead>';
	echo '<tbody>';

	if ( $logs ) {
		foreach ( $logs as $log ) {
			echo wp_kses_post(
				"<tr>
					<td>{$log->id}</td>
					<td>{$log->recipient_email}</td>
					<td>{$log->subject}</td>
					<td>{$log->status}</td>
					<td>{$log->sent_at}</td>
				  </tr>"
			);
		}
	} else {
		echo '<tr><td colspan="5">No emails logged yet.</td></tr>';
	}

	echo '</tbody></table>';
	echo '</div>';
}
Code language: PHP (php)

As usual, don’t use this slop, nor anything you read here because this is my blarg and I can’t be trusted to do anything correct.

Other Posts Not Worth Reading

Hey, You!

Like this kind of garbage? Subscribe for more! I post like once a month or so, unless I found something interesting to write about.


Comments

Leave a Reply