fluidmind
Star God: Fu Star God: Lu Star God: Shou

Fluid Mind PHP EmailHandler Class

Copyright © 2008 by Daniel G. Delaney, Fluid Mind Software
This script is free and open source. You may copy and modify it in any way you wish as long as you keep the copyright information at the top of the script.

This class provides standard functionality for creating and sending an email message using the UTF-8 encoding for the message body and all headers. It can handle plain-text and HTML bodies (or both), and file attachments. You can instantiate it and send a message manually, or you can make a separate class that extends this class for each email message your system needs to send.

Download

Download the PHP script as a zipped file (you might have to right-click that link and choose "Save as"). Unzip it and place it in the directory where you've set PHP to automatically look for your classes (you should always use the __autoload() function to set that).

Usage Examples

Plain text message:

$email = new EmailHandler();
$email->setFrom('joe@example.com', 'Joe Schmoe');
$email->setSubject('This is a test');
$email->setBody('This is a test');
$email->addRecipient('jane@example.com', 'Jane Schmoe');
$email->send();

HTML message with an attachment:

$email = new EmailHandler();
$email->setFrom('joe@example.com', 'Joe Schmoe');
$email->setSubject('This is a test');
$email->setHtmlBody('<html><head><title>This is a test</title></head>' .
    '<body><p>This is a test</p></body></html>');
$email->addRecipient('jane@example.com', 'Jane Schmoe');
$email->addAttachment('/path/to/some/file.txt');
$email->send();

Public Interface

setFrom($email, $name)
Specifies the email address (and optional name) that this message is sent from.
setReplyTo($email, $name)
Specifies the email address (and optional name) that replies will be sent to.
setBounceTo($email, $name)
This sets the email address for bounced messages to go to.
setSubject($subject)
Sets the subject of the email message.
addHeader($headerName, $content)
Adds a mail header.
setBody($body)
Sets the plain-text version of the body of the email message.
setHtmlBody($htmlBody)
Sets the HTML version of the body of the email message.
addRecipient($email, $name)
Adds an email address (and optional name) to the To: header.
addCcRecipient($email, $name)
Adds an email address (and optional name) to the Cc: header.
addBccRecipient($email, $name)
Adds an email address (and optional name) to the Bcc: header.
removeAllRecipients($email, $name)
Removes all To:, Cc:, and Bcc: recipients.
addAttachment($filePath, $mimeType)
Adds a file to attach to the message. (If the MIME type is not specified, the script will try to figure it out.)
send($email, $name, $subject)
Sends the email message. (If you haven't set any recipients with the addRecipient() method you can specify a single recipient with this method.)