O'Reilly logo

PHP in a Nutshell by Paul Hudson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Sending Mail

The primary function for sending email is mail(), which takes three basic parameters and one optional one. These parameters are, in order, the email address to send to, the subject of the message, the body of the message, and finally, any extra headers you want to include. Note that this function relies on a working email server that you have permission to use: for Unix machines, this is often Sendmail; Windows machines, you must set the SMTP value in your php.ini file.

Here is an example of the most basic type of mail() call:

    mail("a_friend@example.com", "My Subject", "Hello, world!");

If you receive mailing errors or don't receive the test mail, you have probably installed PHP incorrectly, or may not have permission to send emails.

You can use variables in place of any of the parameters, like this:

    $mailaddress = "a_friend@example.com";
    $mailsubject = "My Subject";
    $mailbody = "Hello, world!";
    mail($mailaddress, $mailsubject, $mailbody);

To make the email address textual, e.g., "A. Friend" rather than , you need to add both name and address values into the email address, like this:

    $mailtoname = "My Best Friend";
    $mailtoaddress = "a_friend@example.com";
    $mailtocomplete = "$mailtoname <$mailtoaddress>";
    mail($mailtocomplete, "My Subject", "Hello, world!");

With that new code, the email will appear to have been sent to "My Best Friend", which is much easier to read. The fourth parameter is where you specify any number of additional email headers to send ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required