0

I have several forms that send mails. Some of the mails should be sent as html, others as plain text. Right now I set the html option like this:

add_action( 'phpmailer_init', 'mailer_config', 10, 1);
function mailer_config(PHPMailer $mailer){
  $mailer->IsHTML(true);
}

But this implies that all the mails are sent as html. How to change this behaviour on a per-form/mail basis?

3

Here's an (untested) PHPMailer example to check for e.g. the subject and the content type:

function mailer_config( PHPMailer $mailer ) {
    if( 'Subject #1' === $mailer->Subject && 'text/html' !== $mailer->ContentType ) {
        $mailer->IsHTML( true );
    }
}

other options would be to e.g. check the $mailer->From or $mailer->FromName, or some other conditions, depending on your setup.

Another approach without PHPMailer dependency, could be to use the wp_mail filter, with the wp_mail_content_type filter.

0

Ok, following @birgire suggestions, I finally ended up using wp_mail_content_type filter in conjunction with an hidden field on my form. Php code is this:

add_filter( 'wp_mail_content_type', 'set_mailer_content_type' );
function set_mailer_content_type( $content_type ) {
  if(isset($_POST['ishtmlform'])){ return 'text/html'; } // in-page/form hidden field
  return 'text/plain';
}

This allowed me to have more than one form per-page, with different content type settings (for example one that sends text/plain and another that sends text/html, right in the same html page).

Side notes, slightly offtopic:

  • internally, wp_mail() just sets PhpMailer->isHTML(true) if you set content type == 'text/html'. You can find the source in wp-includes/pluggable.php
  • Keep in mind that if you set 'text/html', than you have to send real html code, and by this I mean that message body must contain at least html, head, title and body tags, not just some plain text with some br or link in it, because otherwise it will likely marked as 'not plain text' and your mail indentified as spam.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.