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 ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.