PHP Sending Email
A typical email has three main components:
1. A recipient (represented as an email address)
2. A subject
3. A message body
Sending mail in PHP can be as simple as calling the built-in function mail(). mail() takes up to five parameters but the first three are all that is required to send an email (although the four parameters is commonly used as will be demonstrated below). The first three parameters are:
1. The recipient's email address (string)
2. The email's subject (string)
3. The body of the email (string) (e.g. the content of the email)
A minimal example would resemble the following code:
The simple example above works well in limited circumstances such as hardcoding an email alert for an internal system. However, it is common to place the data passed as the parameters for mail() in variables to make the code cleaner and easier to manage (for example, dynamically building an email from a form submission).
Additionally, mail() accepts a fourth parameter which allows you to have additional mail headers sent with your email. These headers can allow you to set:
the From name and email address the user will see the Reply-To email address the user's response will be sent to additional non-standards headers like X-Mailer which can tell the recipient this email was sent via PHP
The optional fifth parameter can be used to pass additional flags as command line options to the program configured to be used when sending mail, as defined by the sendmail_path configuration setting. For example, this can be used to set the envelope sender address when using sendmail/postfix with the -f sendmail option.
Although using mail() can be pretty reliable, it is by no means guaranteed that an email will be sent when mail() is called. To see if there is a potential error when sending your email, you should capture the return value from mail(). TRUE will be returned if the mail was successfully accepted for delivery. Otherwise, you will receive FALSE.
NOTE: Although mail() may return TRUE, it does not mean the email was sent or that the email will be received by the recipient. It only indicates the mail was successfully handed over to your system's mail system successfully.
If you wish to send an HTML email, there isn't a lot more work you need to do. You need to:
1. Add the MIME-Version header
2. Add the Content-Type header
3. Make sure your email content is HTML
Here's a full example of using PHP's mail() function