Sending Plain-text + HTML Emails in PHP

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:


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:


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");

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

// Send the message
$mail = Mail::factory('mail');
$mail->send('', $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.

Author avatar

About the author

Creator of Surreal CMS and other web things. Follow me for tweets about JavaScript, CSS, and web programming.