Communicating with website users via email is crucial to the success of any online service. The ability to deliver registration confirmations and newsletters, provide a convenient and relatively secure password recovery tool, and keep clients updated with shipping status reports are just a few of the reasons for incorporating email-based features into your website infrastructure. In this tutorial, I'll show you how to incorporate email delivery capabilities into your PHP applications via both its native mail command and a great third-party extension called HTML Mime Mail. I'll conclude the article with a few pointers regarding how to most efficiently carry out bulk email delivery.
Sending email via a PHP script is easy because PHP offers a native function called mail()
. It accepts five parameters, three of which are required and the other two optional. The required parameters include the intended recipient, subject, and message. The optional parameters include additional mail headers and execution options for the mail delivery service. On Unix-based systems this service is by default Sendmail, although you can use other email services such as postfix or qmail, provided that you use sendmail wrappers available to each package. You can specify the location of this service by modifying the configuration directive sendmail_path
. On Windows-based systems PHP requires the address of an SMTP server, specified with the SMTP
configuration directive. The mail() function looks like this:
$to = "firstname.lastname@example.org";
$from = "email@example.com";
$title = "Support subscription confirmation";
$body = <<< emailbody
This email confirms your purchase of a 30 day
email support subscription. Please direct all
requests to firstname.lastname@example.org.
The Example.com support staff
$success = mail($to,$from,$title,$body,
function works great when you want to send just a simple email. However what about sending to multiple recipients? Sending HTML mail? Also, what about sending attachments? While you could use mail()
, additional headers, and some additional programming to perform such tasks, there's another readily available solution that I'd like to introduce.
HTML Mime Mail is a very useful PHP class created and maintained by Richard Heyes (http://www.phpguru.org/
). Available for free download and use under the BSD license, it's a fantastic class for sending MIME-based email. Offering an intuitive OOP syntax for managing email submissions, it's capable of executing all of the email-specific tasks discussed thus far, in addition to features such as handling attachments, sending plain-text emails, and sending HTML emails with embedded images. In this article I'll show you how to take advantage of this great tool.