One of the major uses of a server side scripting language is to provide a way of sending e-mail from the server and, in particular, to take form input and output it to an e-mail address. In this part I will show you how to send e-mail messages using PHP.
The Mail Command
Mail is extremely easy to send from PHP, unlike using scripting languages which require special setup (like CGI). There is actually just one command, mail() for sending mail. It is used as follows:
In this example I have used variables as they have descriptive names but you could also just place text in the mail command. Firstly, $to. This variable (or section of the command) contains the e-mail address to which the mail will be sent. $subject is the section for the subject of the e-mail and $body is the actual text of the e-mail.
The section $headers is used for any additional e-mail headers you may want to add. The most common use of this is for the From field of an e-mai but you can also include other headers like cc and bcc.
Sending An E-mail
Before sending your mail, if you are using variables, you must, of course, set up the variable content beforehand. Here is some simple code for sending a message:
$to = “email@example.com”;
$subject = “PHP Is Great”;
$body = “PHP is one of the best scripting languages around”;
$headers = “From: firstname.lastname@example.org”;
echo “Mail sent to $to”;
This code will acutally do two things. Firstly it will send a message to email@example.com with the subject ‘PHP Is Great’ and the text:
PHP is one of the best scripting languages around
and the e-mail will be from firstname.lastname@example.org. It will also output the text:
Mail sent to email@example.com
to the browser.
Something you may have noticed from the example is that the From line ended with n. This is acutally a very important character when sending e-mail. It is the new line character and tells PHP to take a new line in an e-mail. It is very important that this is put in after each header you add so that your e-mail will follow the international standards and will be delivered.
The n code can also be used in the body section of the e-mail to put line breaks in but should not be used in the subject or the To field.
Mail Without Variables
The e-mail above could have been sent using different variable names (it is the position of the variables in relation to the commas, not the name of them which decides on their use). It could also have been done on one line using text like this:
mail(“firstname.lastname@example.org”,”PHP Is Great”,”PHP