#native_company# #native_desc#
#native_cta#

Sending Email from your PHP Applications Page 2

By Jason Gilmore
on April 15, 2005

Installing Mime Mail

HTML Mime Mail is available for download from Richard Heyes’ website:
http://www.phpguru.org/static/mime.mail.html.
Uncompress the file to a location preferably accessible by PHP’s include_path setting. If this setting isn’t available to you (for instance, you’re using a shared server ISP), then uncompress it to a convenient location. Then include the class in your script using the REQUIRE_ONCE statement. In the following example I’ve placed the HTML Mime Mail directory in the same directory as my script:
require_once(“htmlMimeMail5/htmlMimeMail5.php”);
For this tutorial I’m using HTML Mime Mail version 2.5.1, which was rewritten for PHP 5. Take note that if you’re still running PHP 4, you’ll need to use an earlier version of the class.

Sending an Email

HTML Mime Mail’s object-oriented interface makes sending email quite intuitive. In this first example I’ll assign the sender address, subject, body text, and finally submit the message for delivery:
 <?php

    require_once("htmlMimeMail5/htmlMimeMail5.php"); 

    // Instantiate a new HTML Mime Mail object
    $mail = new htmlMimeMail5();

    // Set the sender address
    $mail->setFrom("[email protected]");
    
    // Set the reply-to address
    $mail->setReturnPath("[email protected]");

    // Set the mail subject
    $mail->setSubject("Test HTML Mime Mail");

    // Set the mail body text
    $mail->setText("This is the body of the test email.");

    // Send the email!
    $mail->send(array("[email protected]"));

?>       

As you can see, HTML Mime Mail offers a much more convenient means for creating and sending email messages than PHP’s native interface. But this is just a sampling of this useful class’s capabilities. Read on to learn more.

Sending to Multiple Recipients

In the last example, you may have noticed the send() method requires that the recipient address is presented as an array element. This is because send() allows for emails to be sent to multiple users by simply appending new elements to the array. The following example sends an email to two users, namely [email protected] and [email protected]:
        // Send the email to [email protected]
$result = $mail->send(array('[email protected]', '[email protected]'));

You can also specify other recipients in the same fashion using the setCc() and setBc() methods.

Sending an Attachment

The question of how to send attachments using PHP’s mail() function comes up quite frequently in newsgroups. I’m happy to forego the gory details of how it’s accomplished in this tutorial, because the HTML Mime Mail class resolves the problem quite easily. In the following example I’ll send an email with an attachment titled htmlmimemail.doc to [email protected]:
<?php

    require_once("htmlMimeMail5/htmlMimeMail5.php");

    // Instantiate a new HTML Mime Mail object
    $mail = new htmlMimeMail5();

    // Set the From and Reply-To headers
    $mail->setFrom("Jason <[email protected]>");
    $mail->setReturnPath("[email protected]");

    // Set the Subject
    $mail->setSubject("Test with attached email");

    // Set the body
    $mail->setText("Please find the new tutorial attached. Thank you!");

    // Retrieve a file for attachment
    $attachment = new fileAttachment("htmlmimemail.doc", "application/vnd.ms-word");

    // Attach the file, assigning it a name and a corresponding Mime-type.
    $mail->addAttachment($attachment);

    // Send the email to [email protected]
    $result = $mail->send(array('[email protected]'));
?>

Sending out HTML formatted email

Personally, I think receiving HTML-formatted email is akin to scratching one’s nails on the blackboard. There’s simply no reason for it. However there has been such an ongoing interest in learning how to do so programmatically that I don’t think this tutorial would be complete without some discussion of the matter. Like attachments, sending HTML-formatted email with HTML Mime Mail is amazingly easy. The following example sends [email protected] an HTML-formatted email with a gray background and a GIF image named advertisement.gif. Note that the second (optional) parameter of the setHTML() method specifies the location of the images that should be embedded in the email. You also have the option of pointing the images to an online location, however keep in mind that some email clients (Squirrelmail for example) will not render these images for reasons of security.
<?php

    require_once("htmlMimeMail5/htmlMimeMail5.php");

    // Instantiate a new HTML Mime Mail object
    $mail = new htmlMimeMail5();

    // Set the From and Reply-To headers
    $mail->setFrom("Jason <[email protected]>");
    $mail->setReturnPath("[email protected]");

    // Set the Subject
    $mail->setSubject("HTML formatted email");

    $html = "
    <body bgcolor='#808080'>
    <img src='advertisement.gif' alt='Buy my book!'>
    </body>";

    // Create the HTML email
    $mail->setHTML($html, "/home/apache/newsletter/images//");

    // Send the email to [email protected]
    $result = $mail->send(array('[email protected]'));

?>

Sending out Bulk Email

Web-based PHP scripts aren’t designed to run for long periods of time (the default execution time is 30 seconds), and this presents a problem if you need to send a weekly newsletter to a large number of recipients. Therefore you’ll want to consider alternative solutions for such purposes. These solutions not only facilitate subscriber management, but also support a wide variety of additional useful features such as auto-responses, web-based subscription/unsubscription, and web-based newsletter administration. As you might imagine, several open source software packages are available. I’ll highlight two of the most popular packages here:

While these open source solutions are indeed powerful, both serve primary roles as mailing list administrators, and accordingly are lacking in a few features one might expect of a newsletter-specific application. For instance, scheduled mailings, response tracking, and custom HTML templates are just a few features that could greatly enhance the utility of this service. That said, if you have a budget available for purchasing third-party services, I suggest taking some time to evaluate a few commercial offerings. I’ll highlight some of the more promising services here:

Conclusion

Alternatively you could take advantage of PHP’s command-line interface (CLI), enabled by default as of version 4.3.0. Using the CLI, you can create scripts that execute directly from the command-line, or on a scheduled basis using a daemon such as CRON. PHP CLI scripts don’t lack any of the features available to you when building Web applications, and have the additional advantage of being able to execute for a long period of time.

About the Author

Communicating via email is a wonderfully effective and cheap means for enhancing your website’s capabilities and keeping users updated regarding your organization’s latest offerings. Using PHP and the great HTML Mime Mail class, doing so programmatically has never been easier. If you found this tutorial useful, I welcome you to email me with your comments and questions at wj AT wjgilmore.com. Thank you!
W. Jason Gilmore (http://www.wjgilmore.com/) is the Open Source Editor for Apress (http://www.apress.com/). He’s the author of Beginning PHP 5 and MySQL: Novice to Professional (Apress, 2004. 748pp.). His work has been featured within many of the computing industry’s leading publications, including Linux Magazine, O’Reillynet, Devshed, Zend.com, and Webreview.