For low-traffic websites, it is reasonable to be informed by eMail when a site’s form is submitted. In principle, sending eMail with PHP couldn’t be simpler: it is a single function, mail, that has just three required arguments: to, subject and message.

<?php
	mail(toaddress@domain.com, 'Subject Line', 'The body of the eMail message’); 
?>

This works for the simplest of messages. But before we proceed, there are several important points to note:

  1. mail relies on a mail server being installed and operational. This is not the default for most of the self-installed server options I recommended earlier. You may want to test your uses of mail from your actual hosting provider.
  2. Many hosting providers will restrict or complicate the use of the mail function in order to avoid poorly written pages being used as spam gateways.  It is your responsibility to investigate any hurdles that may be unique to your hosting setup.

    When testing your eMail routine, make sure you can receive sent eMails promptly and correctly. Certain eMail services update their inbox less frequently; others may have over-zealous spam filters. In my experience, gMail is the best option.

  3. If your form is submitted more than a dozen times a day, you will need to look at a different way of handling the incoming data (e.g. direct insertion of the information into a database).

    Use of the mail function is not the way to handle eMail campaigns. For that, you’ll likely want to use a service such as MailChimp.

  4. Mail sent with the mail function is shown as being sent from the eMail address of the server administrator. Changing this, and a lot more besides, is the remit of a fourth, optional value, headers.

First, the arguments that we have so far can easily be substituted with variables from a form:

<?php
$to = 'youremailaddress@domain.com';
$subject = 'New form completion';
$message = $_POST['comment'];
mail($to,$subject,$message);
?>

(This, of course, assumes that the form information has been validated first – you don’t want to receive an eMail every time the form is filled out incorrectly).

Because the message portion can become very long, it is common to join components together to form the entire message, using a special form of concatenation, along with escaped line returns (note the use of periods and spaces immediately after the second use of the $message variable):

<?php
$message = 'New message from '.$_POST[firstname].' '.$_POST[lastname].': \r\n';
$message .= $_POST['comment'];
?>

The result, sent in the body of the eMail, would include the supplied first and last name of the person who filled out the form, together with their message:

New message from Harry Belafonte:

Day day light an me wan’ go home

For anything more complex than this: sending a "rich" HTML eMail, or showing the eMail as being sent from the person submitting the form, rather than the eMail administrator, we need to modify the eMail headers.