Add a Plain-Text Version to HTML Emails
Generates a plain-text alternative for HTML emails that do not include one, which spam filters like and text-only email clients need.
Opens WPIDE on
Code
add_action( 'phpmailer_init', function ( $phpmailer ) {
if ( 'text/html' !== $phpmailer->ContentType || '' !== $phpmailer->AltBody ) {
return;
}
$text = preg_replace( '#<a[^>]+href=["\']([^"\']+)["\'][^>]*>(.*?)</a>#is', '$2 ($1)', $phpmailer->Body );
$text = preg_replace( '#<(br|/p|/div|/h[1-6]|/tr|/li)[^>]*>#i', "\n", $text );
$text = wp_strip_all_tags( $text );
$text = html_entity_decode( $text, ENT_QUOTES, 'UTF-8' );
$text = preg_replace( "/\n{3,}/", "\n\n", $text );
$phpmailer->AltBody = trim( $text );
} );
Notes
Links are kept as "text (url)" in the plain-text version.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.