How to add text/plain to HTML emails

By default WordPress will send emails as plain text using the content type “text/plain”.

But some plugins, such as Gravity Forms, will send HTML emails.

The issue with this is HTML emails (without the plain text content) are a significant “signal” for spam filters. Making it more likely the emails to end up in the spam folder or to never arrive!

mail-tester.com reports:

MIME_HTML_ONLY
Message only has text/html MIME parts

Fortunately there’s an easy solution – a function which will automatically add the plain text content from the HTML content.

The code below shows how to do this. If you haven’t already I suggest you create create a custom plugin for holding the code.

/* 
Description: Add plain text content to HTML email
Date: 6 January 2019
Author: IT Support Developer Guides
Author URL: itsupportguides.com
*/

class WPDG_Add_Plain_Text_Email {
  	function __construct() {
		add_action( 'phpmailer_init', array( $this, 'add_plain_text_body' ) );
  	}

	function add_plain_text_body( $phpmailer ) {
		// don't run if sending plain text email already
		// don't run if altbody is set
		if( 'text/plain' === $phpmailer->ContentType || ! empty( $phpmailer->AltBody ) ) {
			return;
		}

		$phpmailer->AltBody = wp_strip_all_tags( $phpmailer->Body );
	}
}

new WPDG_Add_Plain_Text_Email();