Sending HTML Mail via SMTP with PHP Pear Mail

May 30th, 2012

Warning: This post is 11 years old. Some of this information may be out of date.

Here's how to send html email via remote SMTP using PHP and Pear Mail / Mime.

Installing Pear Mail

To install the classes you should enter (as a superuser):

pear upgrade
pear install Mail
pear install Mail_Mime
pear install Net_SMTP

Pear Mail Mime Example

The following code shows how to send an HTML mail using Pear classes over SMTP.

<?php
/**
 * send_email
 * Sends mail via SMTP
 * uses Pear::Mail
 * @author Andrew McCombe &lt;[email protected]>
 * 
 * @param string $to Email address of the recipient in 'Name &lt;email>' format
 * @param string $from Email address of sender
 * @param string $subject Subject of email
 * @param string $body Content of email
 * 
 * @return boolean if false, error message written to error_log
 */
function send_email($to, $from, $subject, $body) {
        require_once "Mail.php";
        require_once "Mail/mime.php";    

        $host = "smtp.yourhost.com";

        $headers = array (
                'From' => $from,
                'To' => $to,
                'Subject' => $subject
        );

        $mime = new Mail_mime();
        $mime->setHTMLBody($body);
        
        $body = $mime->get();
        $headers = $mime->headers($headers);

        $smtp = Mail::factory('smtp', array ('host' => $host));
        $mail = $smtp->send($to, $headers, $body);
        
        if (PEAR::isError($mail)) {
                return false;
        } else {
                return true; 
        }
}

$body = '

<h1>
  Test Mail
</h1>

<p style="color: red">
  This is a test
</p>';

send_email('John Doe <John @doe.com>', 'Bob Smith <bob @example.com>', 'Test HTML message', $body);