3

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

Progman
  • 16,827
  • 6
  • 33
  • 48
user3718754
  • 43
  • 1
  • 6

2 Answers2

3

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.

gael
  • 1,314
  • 2
  • 12
  • 20
0

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

$to      = 'test@example.com';
$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      = 'test@example.com';
$subject = 'The subject';
$body    = 'The email body content';
$headers = array('Content-Type: text/plain; charset=\"utf-8\"\r\n');

wp_mail( $to, $subject, $body, $headers );
Bhautik
  • 11,125
  • 3
  • 16
  • 38
  • Hey thanks for your answer, I want to send both options on one mail and not one text mail and one html mail. In the past that was what we used to do for older email softwares that didn't support html well. – user3718754 Apr 10 '21 at 19:26
  • This? https://wordpress.stackexchange.com/questions/191923/sending-multipart-text-html-emails-via-wp-mail-will-likely-get-your-domain-b – Howard E Apr 10 '21 at 22:40
  • Thank you, the solutions on that post seems a bit messy. All of them are using filters and some of the options are really complex which can cause problems on the long run. I hoped there is simpler solution with wp_mail but if it's not possible it will be safer to use only html version. – user3718754 Apr 11 '21 at 10:15