How to Include HTML in the WordPress wp_mail function

One of the many interesting features of the CMS of the moment is wp_mail. A function that allows us to send an email from any point.

It is especially useful when we are programming a plugin or editing one, and we need to send notifications to the user and / or the administrator to notify changes.

Its syntax is:

wp_mail( $destinatario, $asunto, $cuerpo, $cabeceras );

And its main problem is that, by default, it sends a plain text.

How to Include HTML in the WordPress wp_mail function

But everything has a solution! If we want to include formatted text (bold, colors, different fonts or sizes), images, tables, links, etc. We only have to apply any of these two methods:

Method 1: Through the headers

We indicate to the function that the text to be sent contains HTML and therefore must be interpreted as such.

$destinatario = 'sendto@example.com';
$asunto = 'Aquí va el asunto del correo';
$cuerpo= 'El cuerpo del mensaje con todo el HTML que queramos. Por ejemplo:apkvenue.com';
$cabeceras= array('Content-Type: text/html; charset=UTF-8');

wp_mail( $destinatario, $asunto , $cuerpo, $cabeceras);

Method 2: We change that by default the function uses plain text

We must add this text in the functions.php of your active theme, or in your plugin.

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

Did you find this entry useful? Share it to help other programmers like you!

Exit mobile version