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,
<?php mail(email@example.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:
- Many hosting providers will restrict or complicate the use of the
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.
- 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 sent with the
First, the arguments that we have so far can easily be substituted with variables from a form:
<?php $to = 'firstname.lastname@example.org'; $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
<?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.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.