WordPress – How to automatically create email plain text alternative source

The following WordPress PHP function will automatically add the plain text alternative source to outgoing emails.

This provides a non-HTML formatted version of the email, which is sometimes preferred by users and email clients.

If you’re not sure where to place this code I highly recommend you read How to create a WordPress plugin for your custom functions.

class ITSG_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 or altbody is not set
     if( 'text/plain' === $phpmailer->ContentType || ! empty( $phpmailer->AltBody ) ) {
          return;
     }

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

new ITSG_Add_Plain_Text_Email();