PHP Mail

You can use PHP to dynamically send emails to one or more recipients. This can be handy for a lot of reasons.

Some of the benefits of being able to send mail via PHP include:

The PHP mail() Function

To send email using PHP, you use the mail() function. This accepts 5 parameters as follows (the last 2 are optional).

Below is an explanation of the parameters.

Parameter Description
to Required. The recipient's email address.
subject Required. The email's subject line.
message Required. The actual email body.
headers Optional. Additional header fields such as "From", "Cc", "Bcc" etc.
parameters Optional. Any additional parameters.

Sending an Email

You could send email by simply doing this:

Although, in reality, you would probably set your parameters up as variables. Also, if the email was triggered by a user, you would probably provide them with feedback to say that the email had been sent.

HTML Emails

To send an HTML email, the process is the same, however, you need to provide additional headers (as well as an HTML formatted message).

Note that you need to separate each header with a carriage return.

Windows

For Windows systems, use this code:

UNIX

For UNIX systems, use this code:

Difference Between UNIX and Windows Code?

You probably noticed in the above example that there's a Windows version and a UNIX version.

The only difference is in the way the carriage returns are specified. On Windows it's \r\n, on UNIX it's \n.

The PHP specification stipulates that you should use \r\n for creating the carriage returns. This should work fine on Windows systems. UNIX systems however, have a tendency to add \r to the \n, therefore resulting in r\r\n, which of course, wouldn't work. Therefore, we simply leave out the \r on the UNIX version.

Configuring Mail on PHP

The above steps assume that your PHP installation is configured to send mail. Your hosting provider should already have configured PHP to send mail, so you shouldn't need to do anything further if your website is hosted with a third party hosting provider.

If you need to send mail from your local computer, you may need to configure PHP to send mail. The next lesson explains this.