Send HTML Emails In WordPress

HTML emails are much more beautiful than plain text ones. We can have images, formatted text, links in emails which can help us easily and enjoyable reading them. In WordPress, there’re various ways to send emails in HTML format that you’ll see in this post.

317782969 513e089227 Send HTML Emails In WordPress

1. Using headers for HTML emails

The fact is wp_mail supports (nearly) same parameters as mail function (they have the same first 4 parameters, the last one is different):

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

So, we can add headers for HTML emails just like we do with mail function:

$headers = 'Content-type: text/html';
wp_mail( $to, $subject, $message, $headers );

The difference in WordPress is you can write headers as a string or as an array (useful when you want to add more headers). Both work.

$headers = array( 'Content-type: text/html' );

Note: This method affects only on one email. If you want to make all emails in HTML format, you should use filters as below.

2. Using WordPress filters

Similar to how we change from name and from email address in WordPress, we can change the content type of emails to HTML using filters.

Change content type

add_filter( 'wp_mail_content_type', 'rw_change_email_content_type' );
function rw_change_email_content_type( $content_type )
{
    return 'text/html';
}

Change full headers

WordPress has a filter that allow us to change all parameters for wp_mail function, that filter is wp_mail. So, in our case, to change headers, we can do as the following:

add_filter( 'wp_mail', 'rw_change_email_headers' );
function rw_change_email_headers( $params )
{
    $params['headers'] = 'Content-type: text/html';
    return $params;
}

The benefit of this method is you can add as many headers as you want like Mime-Type, CC, BCC, etc.

3. Change PHPMailer object

We know that wp_mail uses PHPMailer to send emails. And before sending emails, WordPress use a filter phpmailer_init to change the PHPMailer. We can use it to add our headers for HTML emails, like this:

add_filter( 'phpmailer_init', 'rw_change_phpmailer_object' );
function rw_change_phpmailer_object( $phpmailer )
{
    $phpmailer->IsHTML( true );
}

This method is useful when you want to do other things with PHPMailer object such as configure for SMTP.

If you want your HTML emails look good, you can use templates from Mailchimp (it’s free and well documented). Enjoy HTML emails!

4 Comments

  1. Do I need to enter all this stuff within the functions.php file?

    If not, please let me know into which file do I need to add this stuff.

    Reply
    • Just put it in functions.php, it will work. Or better: create a functionality plugin and put this stuff inside.

      Reply
  2. Thanks for sharing these nice tips. These will surely help me in my future WordPress projects.

    Reply

Leave a Reply