Save WordPress emails to the filesystem

There is no shortage of WordPress plugins that disable or log the sent emails. You can pick your favorite, but lately, I reach for a solution that I found in the WordPress.com VIP Support repo.

Since wp_mail is a pluggable function, the implementation can be overwritten from a plugin. The approach that WordPress.com VIP Support takes is writing the email to a filesystem. Perfect for dropping the code below in a single file mu-plugin called wp-mail-save-to-filesystem.php.

Here's the slightly modified version that I used the last time:

function wp_mail($to, $subject, $message)
{
$uploadsDirInfo = wp_get_upload_dir();
$storageDir = trailingslashit($uploadsDirInfo['basedir']) . 'wp-mail';
 
$fileName = sanitize_file_name(time() . "-$to");
$filePath = trailingslashit($storageDir) . $fileName;
 
$content = "TO: $to" . PHP_EOL;
$content .= "SUBJECT: $subject" . PHP_EOL . PHP_EOL;
$content .= $message;
 
if (!is_dir($storageDir)) {
mkdir($storageDir);
}
 
return (bool)file_put_contents($filePath, $content);
}

This does not save the attachments, but that would be doable too!