Simple SMTP HTML E-Mail Class in PHP with PEAR
Posted on Wednesday, July 7, 2010 at 12:44AM by Jack Servedio
Sending an e-mail, whether plain-text or HTML, through an SMTP server, with authentication, in PHP can be done fairly simply using the PEAR Extension. Although sending an SMTP e-mail is fairly simple in concept, it requires a lot of steps to implement which subsequently creates a lot of lines of code. Looking at an example from a PEAR forum, you can see sending a simple HTML e-mail requires you to create an SMTP object, generate headers, and create a Mime object. After creating the Mime object, you have to set the body HTML, Plaintext, From, and Subject from configuration using individual member functions and then use the get method to create the body of the e-mail. Once you have a body, you have to create the e-mail's headers manually from an array. After the e-mail is all ready to send, you have to create a Mail object which will allow you to authenticate with a SMTP server specified by hostname, username, password, and an authentication flag. After you are authenticated and all the other parts of the e-mail are set up, you can call the send function to put everything together and send the e-mail. To send a simple e-mail, you may end up writing 20 - 60 lines of code, not including your configuration variables storing things like hostname, username, password, etc. Sending additional e-mails isn't so simple either, and requires a new Mime object.
However, the class I have written will do all of the heavy lifting by creating objects and putting everything together automatically. You can send HTML e-mails with 2 lines of code, excluding configuration, and send additional e-mails with a single line of code. You can also access the objects created by the class directly if needed or through neat accessor methods. Instead of writing all of the code required in the example from the PEAR forum, your code can look like this:
//Include Class and SMTP Server Configuration
//Instantiate new Class using variables from Config
$email = new SMTPMail( $smtp_host, $smtp_user, $smtp_pass, $smtp_from );
//Set To E-Mail Address, Subject, and (HTML) E-Mail Body [Optionally Plaintext Replacement if HTML Disaabled]
$to = "email@example.com";
$subject = "SMTPMail Class Test E-Mail";
$body = "<h1>SMTPMail Class Test Message</h1><p>This message was sent using the SMTPMail Class which easily sends HTML Based E-Mails using the PEAR Mail Package</p>";
//Send the E-Mail Message
$email->sendMail( $to, $subject, $body );
//Output the E-Mail Status Message
As you can see, this is far simpler than writing all of the code in the example, and wraps up all the functionality in one, easy to use class. You can re-use the class to keep sending additional e-mails from the SMTP server defined in the constructor by simply calling the sendMail method.
Download Source - Source includes the SMTPMail.class.php, a configuration file, and a sample driver to explain how to use the class.