skip to Main Content

I want to send both HTML and Plain Text emails using wp_mail() function in wordpress

I wasn’t able to find a way to do that.
Does anyone know how to do that?

In PhpMailer for example there was an option to set both HTML and text with this line:

$mail->AltBody = $plain_text_format_mail;

Does anybody know if there is something similar for wp_mail that allow me to send both html as the main email and text as a fail safe option?

Thanks

2

Answers


  1. use Content-Type: text/html for HTML email.

    $to      = '[email protected]';
    $subject = 'The subject';
    $body    = 'The email body content';
    $headers = array('Content-Type: text/html; charset=UTF-8');
    
    wp_mail( $to, $subject, $body, $headers );
    

    use Content-Type: text/plain for plain email.

    $to      = '[email protected]';
    $subject = 'The subject';
    $body    = 'The email body content';
    $headers = array('Content-Type: text/plain; charset="utf-8"rn');
    
    wp_mail( $to, $subject, $body, $headers );
    
    Login or Signup to reply.
  2. I was also looking to send both plain text and html mail to get a better score on mail-tester.com

    Hopefully I found this code snippet to add to you custom plugin, child-theme functions.php or even with the wp code snippet plugin:

    /* 
    Description: Add plain text content to HTML email
    Date: 6 January 2019
    
    Author: WP Developer Guides
    Author URL: wpdevguides.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();
    

    This automatically associates a plain text version of your HTML email without modifying the common wp_mail function.

    eg:

          wp_mail($to, $mail_subject, $body, $headers);
    

    And now mail-tester.com is happy with my email contents.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search