Quackit Logo
HTML
CSS
Scripting
Database
Hosting
Design
XML

PHP Mail

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

  • Sending newsletters to a mailing list
  • Sending a "welcome" email to new members of your website
  • A user has just made a purchase and you need to send them a receipt by email
  • Sending an email alert to your technical administrator whenever an error occurs
  • Many more reasons...

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

Code

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:

Code

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.

Code

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:

Code

UNIX

For UNIX systems, use this code:

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.

Enjoy this page?

  1. Link to this page (copy/paste into your own website or blog):
  2. Link to Quackit using one of these banner ads.

Thanks for supporting Quackit!

Sponsored Link: Design CODE-FREE Websites