Question

Is it is possible to send emails with the wp_mail() function having its Content-Type: multipart/alternative ?

I need to send emails that can be shown as HTML or Plain Text depending on what medium interprets the email.

Any suggestions are welcome!

Was it helpful?

Solution

It's right there in the wp_mail() documentation (under Usage):

The default content type is 'text/plain' which does not allow using HTML. You can set the content type of the email either by using the 'wp_mail_content_type' filter (see example below), or by including a header like "Content-type: text/html". Be careful to reset 'wp_mail_content_type' back to 'text/plain' after you send your message, though, because failing to do so could lead to unexpected problems with e-mails from WP or plugins/themes.

(emphasis mine)

The 2nd example on the page shows you how to do it (the example uses text/html but you should be able to use your multipart/alternative instead.

OTHER TIPS

It's totally possible when you have access to the phpmailer instance.

if ($is_html) 
    add_action('phpmailer_init', 'fix_mimeheader');

// more code.

wp_mail( $to, $subject, $html_message, $headers, $attachments );

// ...

function fix_mimeheader( $phpmailer ) {
     // Generate $text_message here.
     // ...

     $phpmailer->AltBody = $text_message;
}

The message sent to wp_mail should be your html code. You also shouldn't include any content type headers. I currently use from, cc and reply-to in the plugin i've made.

If the email is being sent as HTML, I run the action which sets the AltBody property on the phpmailer object directly. This then causes the proper flags to convert the email to a multipart/alternative email.

You can use the wp_mail_content_type filter, which was now been documented in the Codex.

The wp_mail documentation about resetting the content type back to 'text/plain' is kind of misleading, IMO. Since this is a filter, you don't really "reset" it. What you need to consider in your filter is some conditional logic to determine when you need to use multipart vs. plain text or html:

add_filter( 'wp_mail_content_type', 'my_mail_content_type' );
function my_mail_content_type( $content_type ) {

    if( $some_condition ) {
        return 'multipart/mixed';
    } else {
        return 'text/plain';
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top