PHP's
native capabilities for sending e-mail make e-mail distribution from
your web site a breeze. Learn how to use one of PHP's most practical
features.
No matter what type of web site you're building these days, chances
are you'll need to create an automated mechanism for sending e-mail to
various parties. The applications for this type of mechanism really are
countless. Consider these common functions:
- Sending a visitor's contact form query to the appropriate staff member's inbox
- Forwarding a post-purchase order receipt to a customer's e-mail address
- Providing a forgetful user with a password recovery link
- Asking a newly registered user to confirm his e-mail address
The most commonplace way to send these e-mails is through the
server-side language you're using to power the web site, and perhaps
the easiest language to use in this regards is PHP.
In fact, PHP's ability to send e-mail is so heralded that developers
often tout this particular feature as a symbol of the language's
practicality. In fact, to send an e-mail from a PHP-powered web site,
all you need to do is call the native mail() function like this:
mail("jason@example.com", "Welcome to the Website",
"Thank you for registering!");
If you execute this code on any PHP-enabled server running Sendmail, the owner of the address jason@example.com should soon receive a message with the subject Welcome to the Website and the message body
Thank you for registering!.
If you also have the recipient's name available, you can modify the
recipient parameter to reflect the name, provided the format of the
parameter complies with the specifications found in RFC 2822. For instance, the following would be perfectly acceptable:
mail("Jason Gilmore <jason@example.com>", "Welcome to the Website",
"Thank you for registering!");
Of course, the typical message body is presumably much longer than
what's in this example, so feel free to expand the message as you see
fit. Later in this tutorial, I'll show you an easy way to manage longer
message bodies.
Manipulating Message Content and Headers
Take a look at
Figure 1,
which shows the content and headers of the example message, although
for purposes of demonstration I changed the recipient to my own address.
In particular, take note of the sender's address, which is identified as apache@yourserver.com. If a sender address isn't specified within an optional parameter of the mail() function, PHP will automatically use the owner of the server daemon (in this example, that owner was named apache). It's unlikely this is your intent, so you can change the sender address like so:
mail("jason@example.com", "Welcome to the Website", "Thank you for registering!",
"From:support@example.com");
You can also use this optional fourth parameter to pass along other options, such as the Reply-To
address. For instance, if you'd like the recipient to send a reply to
an address other than that used by the sender, you can do so like this:
mail("jason@example.com", "Welcome to the Website", "Thank you for registering!",
"From:support@example.comrnReply-To:help@example.com");
Notice the rn delimiter, which separates each header in the optional parameter. This is required for this feature to work properly! Neglecting to use this delimiter will likely produce unexpected results.
CCing and BCCing Other Recipients
Suppose you created a web-based client support solution and wanted
to CC the client's sales representative whenever the client submitted a
support request. You can use the aforementioned fourth optional
parameter to add the CC, like this:
mail("support@example.com", "Support Request #81K1879", "I need help!",
"From:client@example.orgrnCC:salesrep42@example.com");
You can also BCC the representative in an almost identical fashion:
mail("support@example.com", "Support Request #81K1879", "I need help!",
"From:client@example.orgrnBCC:salesrep42@example.com");
Managing Message Bodies
Attempting to embed multiple-line message bodies directly into the mail()
function is going to result in a maintenance nightmare. For instance,
what if your marketing staff insisted on editing this text? Surely, you
wouldn't want them touching the code directly! As an alternative, you
can store the message body text in a separate text file (or even
database), and then pass that text into the mail() function via a variable:
include "shipping-email.php";
mail("john@example.net", "Example.com: Your order has been shipped!", $message);
Within the shipping-email.php file, I'll embed the message using PHP's heredoc syntax:
<?php
$message = <<<MESSAGE
Dear Customer,
We're pleased to inform you that your order shipped today!
Thank you,
The Sales Staff
MESSAGE;
?>
If you were pulling information from a database and would like to
customize the message body, you can identify variables within the heredoc string, and those variables will be parsed before $message is passed to the mail() function:
$name = "Jason Gilmore";
include "shipping-email.php";
mail("john@example.net", "Example.com: Your order has been shipped!", $message);
You also need to update the revised message body string to include the variable:
<?php
$message = <<<MESSAGE
Dear $name,
We're pleased to inform you that your order shipped today!
Thank you,
The Sales Staff
MESSAGE;
?>
Including Attachments and Sending HTML-formatted E-mail
If your e-mail needs are of a more sophisticated sort, involving
either including attachments or sending HTML-formatted e-mail, check
out the PEAR's Mail and Mail_Mime packages. Used together, these packages make it trivial to perform tasks that are otherwise rather tedious when using the mail()
function alone. For instance, the following code makes enables you to
include and send an attachment along with an e-mail (after
you've installed the Mail and Mail_Mime packages, of course):
include "Mail.php";
include "Mail_Mime.php"
$headers = array (
'To' => 'jamie@example.org',
'From' => 'sales@example.com',
'Subject' => 'Your order has shipped!'
);
$mailMime = new Mail_mime();
$mailMime->addAttachment('/home/receipts/jamie.pdf', 'application/pdf');
$mailMime->setTXTBody($email);
$body = $mailMime->get();
$hdrs = $mailMime->headers($headers)
$mail =& Mail::factory('mail');
$mail->send('jamie@example.org', $hdrs, $body);
See the PEAR's Mail and Mail_Mime documentation for more information about these great packages.
Caveat "Sender"
Two aspects of sending e-mail with PHP commonly confuse people:
- The mail() function doesn't work by default on the Windows platform. This is because Windows does not come bundled with Sendmail. However, by modifying your php.ini file's SMTP, smtp_port, and sendmail_from directives, you can make PHP use a remote SMTP server for mail delivery instead.
- The mail() function is not intended for sending large quantities of e-mail. So, don't expect to create a replacement for a robust mail management solution such as
Mailman.
Where to From Here?
PHP's native mail() function offers most developers
everything they'll need to get started sending e-mails directly from
their web sites. However, several other solutions exist if your needs
surpass mail()'s capabilities. Check out the following resources for more information:
- PHP's native mail() function: If your e-mail needs are fairly straightforward, then PHP's native mail() function is the easiest way to get started.
- The PEAR Mail package:
If you'd like to send attachments or HTML-formatted messages, PEAR's
Mail package offers all of the features you'll need to get the job done.
- The Zend_Mail Component: If you're a Zend Framework user, the Zend_Mail component makes creating and sending e-mails incredibly easy.
- Sending E-mail Using PHP: Watch this free 11+ minute tutorial on PHP's e-mail features over at EasyPHPWebsites.com
- Original Article