Article
Advanced email in PHP
Sending Plain Email
It doesn't come much easier than the procedure to send plain text email in PHP. In fact, you can do it in just one line in a PHP script:
<?php
mail('recipient@some.net', 'Subject', 'Your message here.');
?>
The above line would send an email message to recipient@some.net with 'Subject' as the subject line and 'Your message here.' as the message body. As you can see, PHP's mail function makes sending email exceedingly simple, but there are a few advanced tricks we can use to get more out of this simple function.
First of all, if the mail system you configured in your php.ini file rejects a message you try to send (for example, if the 'to' address is not a valid email address), this function will display an error message in the user's browser. Like most PHP functions, however, error messages may be suppressed by preceding the function name with an @ symbol. Combine this with the fact that the mail function returns either true or false depending on whether the email was accepted by the mail sending system, and you have a formula to send email with appropriate error checking:
<?php
if (@mail($to, $subject, $message)) {
echo('<p>Mail sent successfully.</p>');
} else {
echo('<p>Mail could not be sent.</p>');
}
?>
Note that just because an email message could be sent doesn't guarantee it will arrive at its destination. An email address can be valid (i.e. correctly formed) but not actually exist. For instance, you can successfully send a message to nonexistant.user@hotmail.com -- that is, the mail function will return true -- but the message will bounce because no such user exists. PHP provides no built-in means of detecting when this happens.
When you want to send a message to multiple recipients, you can just list their email addresses one after another, separated by commas, in the first parameter. For example:
<?php
mail('recipient1@some.net, recipient2@some.net',
'An email to two people', 'Message goes here.');
?>
That about covers the basics of the mail function; now let's really get fancy and explore mail headers and what we can do with them!