How To Generate and Send Mail
Understanding the Mail Function
It is a very common task to send input data from web form to email. In this tutorial, we will look at how to generate and send emails with PHP.
Introduction to sending email from PHP scripts
PHP provides a convenient way to send email through the mail() function. This function is a great way to send mail using a simple and standard interface that hides the complexity and quirks of various system programs that are responsible for sending mail. (Sendmail and Qmail are two examples of popular mail programs you would have to talk to directly if the mail() function did not exist). This tutorial will introduce you to the basics of sending mail from PHP scripts and making a simple feedback form.
The mail() function accepts three required values and one optional value. It returns a value indicating success or failure. The email address of the recipient (or To: field), the subject of the message (or Subject: field), and the message body can all be specified through parameters. An optional string containing extra headers can be specified.
mail (string $msgTo, string $msgSubject, string $msgBody, string $extraHeaders);
To send a message, you simply fill in the parameters. This example uses literal strings to illustrate the general usage of the function. The first parameter specifies the email address we are sending mail to. The second is the message subject. I used the third optional parameter to set the "From:" header to an address where I wanted replies to go and added a "X-Mailer:" header to help mail administrators identify the message as originating from an automated source.
When you create a custom header string, remember to separate each additional header with a linefeed ( ). Otherwise, the message text may become garbled. Messages sent through the mail() function are in plain text.
mail ("email@example.com", "Use PHP Everyday", "Don't forget to floss and use PHP everyday!", "From: firstname.lastname@example.org X-Mailer: My PHP Script");
Most of the time, you won't be specifying these values using literal strings, but through variables. You may want to obtain these values from an included php script fragment (an "initialization file") or from a form submission. It's likely you'll want to use values submitted by a form or generated programmatically to send a message. In that case, we substitute string variables for the literal strings used in the previous example.
mail ($strMailTo, $strSubject, $strBody, $strXHeaders);
|Pages: 1 2 3 4 5||Next: Adding Extra Header Information »|