Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page