avatar Deluxe Blog Tips About Projects

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.

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', function () {
    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', function( $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', function( $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!

🔥 HOT: Interested in boosting your WordPress SEO? My Slim SEO plugin is a super lighweight and automated plugin that handles most the hard work for you: meta tags, sitemap, redirection, schema & link building.

👉 Have a look and you will love it: wpslimseo.com