Sending Plain-text + HTML Emails in PHP

A note from A Beautiful Site’s founder: We developed Surreal to be easy for you and your clients. If you’re a web designer, you should take a look at the simple, hosted CMS that’s changing the way content is managed. Surreal integrates in moments and is trusted by over 18,000 websites. Try it out for free and let us know what you think! Visit Website »

You can easily add some basic headers and send HTML emails using the PHP mail() function, but sometimes the resulting messages don’t seem to display correctly in certain email clients — especially those that don’t support HTML emails.  The best thing to do is send both a plain-text version and an HTML version of your message in the same email.

Enter PEAR

Fortunately, the PEAR project makes this really easy.  First, you’ll need to make sure the following PEAR packages are installed:

Mail
Mail_Mime

To do this from a terminal window, just type pear list.  If the aforementioned packages aren’t showing as installed, you’ll need to install them.  Although installing PEAR packages is beyond the scope of this article, you can usually get them installed with the following commands.  (You may need to use sudo or be logged in as root for this to work.)

pear install mail
pear install mail_mime

Preparing the Email

Once PEAR is enabled, preparing the email is really simple.  First, you’ll need to include the required PEAR classes:

include('Mail.php');
include('Mail/mime.php');

Once that’s out of the way, you can send HTML/Plain-text emails with the following code:

// The content of the message in both plain-text and HTML
$message_text = '...';
$message_html = '<html>...</html>';

// Set the message content
$message = new Mail_mime("\n");
$message->setTXTBody($message_text);
$message->setHTMLBody($message_html);

// Get the body and headers
$body = $message->get();
$headers = $message->headers(array(
	'From' => 'Sender Name <sender@example.com>',
	'Subject' => 'This is the subject of the message'
));

// Send the message
$mail = Mail::factory('mail');
$mail->send('recipient@example.com', $headers, $body);

Of course, if you’re using template files for your emails you could replace the first couple of lines with something like this:

$message_text = file_get_contents('message.txt');
$message_html = file_get_contents('message.html');

This, of course, will populate the email with the contents of both message.txt and message.html.

If you enjoyed this article, please share it with a friend!

One Response to Sending Plain-text + HTML Emails in PHP

  1. I was wondering if there might be a solution like this without using Pear?

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>