I have made a plugin that will send out an email every time a new post is published in WordPress to the admin (eventually this will go to subscribers). Within my plugin I have a email template in table format which is below.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Email test</title>
</head>
<body>
<table cellpadding="0" cellspacing="0" border="0" id="backgroundTable">
<tr>
<td valign="top">
<table cellpadding="0" cellspacing="0" border="0" align="center">
<tr>
<td width="20" valign="top"></td>
<td width="560" valign="top">%%CONTENT%%</td>
<td width="20" valign="top"></td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
I string replace the %%CONTENT%% with the content from the post. I have tried running the content through various functions and filters including: apply_filters, htmlspecialchars() and htmlentities() with no success. When I receive the email in Outlook it has weird characters in it. My post contains some special characters like £, &, “, ’ and the degree symbol °C.
This is the plugin code:
function post_published_notification( $ID, $post ) {
global $post;
$author = $post->post_author; /* Post author ID. */
$name = get_the_author_meta( 'display_name', $author );
$email = get_the_author_meta( 'user_email', $author );
$title = $post->post_title;
$to[] = sprintf( '%s <%s>', $name, $email );
$subject = sprintf( 'Published: %s', $title );
$content = $post->post_content;
$content = apply_filters('the_content', $content);
$html_content = file_get_contents(__DIR__.'/email_components/email.html');
$message = str_replace('%%CONTENT%%', $content, $html_content);
$headers[] = 'MIME-Version: 1.0' . "rn";
$headers[] = 'Content-type: text/html; charset="UTF-8' . "rn";
wp_mail( $to, $subject, $message, $headers );
}
add_action( 'publish_post', 'post_published_notification', 10, 2 );
So my question is how do I get these characters to safely display correctly in the email subject and email body? Many thanks! Mike
In the end after trying many different options I solved this by using the wordpress loop to output my email content: