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:

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.

Author avatar

About the author

New Hampshirite building web apps in Florida. Creator of Surreal CMS, Postleaf, and DirtyMarkup.

Need to get in touch? Catch me on Twitter.