The Basics
PHP provides a handy function for mailing from a server. On a basic level, all you need to do is call the function mail with three parameters, which has the following syntax.
bool mail(string $to, string $subject, string $message [, string $headers][, string $additonal_params]])
These parameters are pretty straight forward. Below is an example of how to send a very simple email message with no headers.
1
2
3
4
$to = "example@wisc.edu";
$subject = "This is an example email.";
$message = "Here is my message. Hopefully this email works!";
mail($to, $subject, $message);
1 2 3 4 |
$to = "example@wisc.edu"; $subject = "This is an example email."; $message = "Here is my message. Hopefully this email works!"; mail($to, $subject, $message); |
Some notes about this basic usage:
- To specify a newline in the message, use the '\n' character.
- To specify multiple recipients, simply seperate each address by a comma in your $to string.
- Being able to mail from php requires that your sendmail properties are set in php. Typically this is done for you -- if you are starting your own server, however, you may have to initialize these variables by yourself.
Using Headers
Of course, modern email messages consist of much more than a subject, message, and receiver. We may want to specify who the message was from, the date, the organization responsible for the email, etc. PHP uses the $header string to specify all of these fields and more. Each line of the header field (seperated by a '\n' character) represents a single entry in the header. The syntax for a header entry is simply:
<Header Field>: value of the field
Below is an example of making a header in php and then calling mail with this header.
1 2 3 4 |
$header = "From: John Doe <john.doe@example.com>\n" . "To: The Receiver <receiver@example.com>\n" . "cc: Example Group <group@example.com>"; mail("john.doe@example.com", "Test Subject", "Hi\n\nHere is my message.", $header); |
Some commonly used headers in PHP are:
| From: | The email address, and optionally the name of the authors. |
| To: |
The email addresses of the recipients, and optionally their name. |
| bcc: |
Blind Carbon Copy: Addresses to receive a copy of the email, but who do not appear in the recipient list. |
| cc: |
Carbon Copy: Addresses to receive a copy of the email, but who are not directly referred to in the email. |
| Sender: |
Address of the actual sender acting on behalf of the author listed in the From: field |
Sending Attachments
Attaching a file in an email is something that is very common. Unfortunately, attachments are not trivial in PHP. A seperate article dedicated to this topic is currently in the works on The Tech Repo -- it will be linked here once it is completed.





