. */ defined( 'ABSPATH' ) OR exit; class Add_Plain_Text_Email { /** * Add hooks */ public function add_hooks() { add_action('phpmailer_init', array( $this, 'set_plaintext_body' ) ); } /** * @param PHPMailer $phpmailer * * Note: somehow we can not type-hint the parameter here as PHPMailer... */ public function set_plaintext_body( $phpmailer ) { // don't run if sending plain text email already if( $phpmailer->ContentType === 'text/plain' ) { return; } // don't run if AltBody is set (by other plugin) if( ! empty( $phpmailer->AltBody ) ) { return; } // set AltBody $phpmailer->AltBody = $this->strip_html_tags( $phpmailer->Body ); } /** * Remove HTML tags, including invisible text such as style and * script code, and embedded objects. Add line breaks around * block-level tags to prevent word joining after tag removal. */ public function strip_html_tags( $text ) { $text = preg_replace( array( // Remove invisible content '@]*?>.*?@siu', '@]*?>.*?@siu', '@]*?.*?@siu', '@]*?.*?@siu', '@]*?.*?@siu', '@]*?.*?@siu', '@]*?.*?@siu', '@\t+@su', '@\n+@su' ), '', $text ); // replace certain elements with a line-break $text = preg_replace( array( '@ elements $text = preg_replace( '@]+href=["\']([^"\']+)[^>]+>(.+)@iu', "\$2 (\$1)", $text ); // strip all remaining HTML tags $text = strip_tags( $text ); return trim( $text ); } } $apte = new Add_Plain_Text_Email; $apte->add_hooks();