Allow WordPress to use HTML in emails

WordPress allows you to easily send emails with a simple wp_mail() function. This function is used by WordPress itself, themes and plugins use it, yet you could use one to send emails manually when needed.

This simple function works like a charm, but the downside is that, by default, it sends messages as plain text only. While there’s nothing wrong with the plain text, if you’re sending custom messages, you’ll probably need HTML tags in the messages. By adding HTML in messages, you can automatically create links for your users, you can leave images, videos and your logos.

So, to make HTML work when sending emails with wp_mail() function, you will need to inform WordPress about that.

Luckily, WordPress developers were kind enough to create a filter which will do the work for us. We’ll break down the entire process into 3 simple steps:

The function:

Before you can call your wp_mail(), you will need the following function:

function wploop_email_content_type() {
return 'text/html';
}
add_filter( 'wp_mail_content_type', 'wploop_email_content_type' );

Sending emails:

After this function, you can send an email by adding something like:

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

Resetting content type:

As we mentioned earlier, this function is used by many themes and plugin developers. Many of them are using its default option and still forcing the plain text to be sent in emails. While the function would work just fine if you only c/p it in functions.php file, by doing so you would change the content type globally. That means that some themes and plugins would end up with errors while sending emails and even WordPress itself could have problems when sending an email which allows users to retrieve lost passwords. In order to avoid conflicts, you need to reset the content type after sending your email:

remove_filter( 'wp_mail_content_type',' wploop_email_content_type ' );

If you include all 3 steps while sending emails via wp_mail() function, you shouldn’t have any problems implementing your own email functions in your theme or plugin. Now you can focus on creating HTML email which will draw user’s attention and fulfill its purpose.

START YOUR OWN BLOG

This guide is an introduction to mastering the art of blogging. It provides easy to follow steps to start, maintain, and grow your blog.

Read the guide

Leave a Reply

Your email address will not be published. Required fields are marked *