bembry.org
Home / Technology / Web_development / Php

mail() Function

mail() Basics
PHP has a built-in function for sending email called "email()". The email() function requires three pieces of data: the mail-to address, a subject, and the body of the email. Each of these pieces of information may be assigned to a variable and then fed into the function or else coded directly as a string. The sample below uses variables to pass the information to the mail() function.

<?php
$mail_to = "feedback@bembry.org";
$subject = "Feedback Information";
$mail_text = "Input from web site \n";
$mail_text .= "Visitor's Name: $visitor \n";
$mail_text .= "Wants on email list: $mailme \n";

if (mail ($mail_to, $subject, $mail_text))
echo "Mail send successfully.";

else
echo "Error sending mail. Please contact site administrator"
?>

The first section of code sets the varibles equal to values we want. These variables could just as easily have been passed in from a form input or something. Note that there are three lines assigning values to the $mail_text variable. The first line uses a regular equals sign =, but the last two use a period and an equal sign .= . The line that has a plain equals sign is creating the variable and filling it with information, while all the lines that use a .= are adding extra information to the variable. This is called concatentation. So, after the second $mail_text line, $mail_text has the value "Input from web site \n Visitor's Name: $visitor \n". You may use the concatenation code as many times as you like.

Note also in the script above the code \n. These two characters together tell the script to enter a line break and start the next bit of text on a new line in the email.

Finally, note how the mail() function was encased inside an if() function. This construction provides some error checking capability to the code. It tells the computer to run the mail() function and if it is successful, then give the success message, but if it fails, give the error message.

Customizing mail() values
In the code above, the mail() function will send the email to the designated address with the appropriate subject line, but in the user's email, the "from" field will read "root" or something else that does not make much sense. The mail() function can be customized to show any data desired in the "From:", "Reply to:", "CC:" and other fields using the following syntax:

mail($mail_to, $subject, $mail_text, "From:$user_name \r\n Reply-to: mom@hotmail.com \r\n Cc:everyone@hotmail.com");

Notice that these extra data entries are contained all together in quotation marks and are separated by \r\n. By including the $user_name variable in the "From:" field, the email will appear to have come from the user himself.

Restricted access