Sending HTML mail through Wordpress

Posted:

I’ve been working with the PHP CMS WordPress a lot lately. It’s a pretty simple system that doesn’t make its internals hard to get to, which I appreciate.

One of the internal functions WP provides is wp_mail. This, you might have guessed, is used to send SMTP mail. The parameter list for this function is a bit long and long parameters lists are hard to remember:

wp_mail( $to, $sub, $body, $hdrs, $attach );

These parameters are pretty self-evident: mail recepient, subject line, body of message, SMTP headers, attachments. The last two parameters are optional. This works great for sending plain, unformated text messages. However, you may want to tweak this a bit.

The first thing you might want to do is change the default sender. This is done by adding a header:

$to = "nemo@uptopia.com";
$sub = "Your submarine parts";
$msg = "I have the new parts for your fabulous machine.";

$headers = array("From: Joe Johnston <jjohn@taskboy.com>");
$h = implode("\r\n",$headers) . "\r\n";

wp_mail($to, $sub, $msg, $h);

This makes the email look like it was sent by me even though the the web server process running the PHP script isn’t owned by my account.

Another common task is to send HTML-formated email using this system. To do this, you must change the content type of the message to text/html. This is most easily done through the headers, even though you are supposed to be able to do this through the filter wp_mail_content_type. In my testing, this did not work, but the following code did:

$to = "nemo@uptopia.com";
$sub = "Your submarine parts";
$msg = "<html><body><h1>Awsome news</h1>
    <p>I have the new parts for your fabulous machine.</p>
    <address>--Joe</address>";

$headers = array("From: Joe Johnston <jjohn@taskboy.com>",
             "Content-Type: text/html"
             );
$h = implode("\r\n",$headers) . "\r\n";

wp_mail($to, $sub, $msg, $h);

By adding the content type to the headers, the recipient’s email client should format the message accordingly.

Of course, sending HTML email has risks. It could be caught in spam filters. The client may not support HTML formatting (although that’s rare). The client may disable email HTML from using javascript, CSS or grabbing remote assets like images.

Caveat Spammer.