Email With PHP
Let visitors email you using a form from your site. Enough said.
Step 1: Syntax
The very first step is knowing the format of the email function of PHP. Here it is:
mail(address,subject,message,headers)
Italicized words are the ones we need the values for. The first, address, is your email address. The next 2 are self-explanatory. Headers is the string that sets values for headers (the "From" part of the email).
Step 2: The Form
Knowing the values that we need, next comes making the form to get them. We make a file called email.html and here's the code:
<form action="sendemail.php" method="post"> Name: <br><input type="text" name="Name" size="30"> <br>Email: <br><input type="text" name="Email" size="30"> <br>Subject: <br><input type="text" name="Subject" size="30"> <br>Message: <br><textarea cols="30" rows="5" name="Message"> </textarea> <br><input type="submit" value="SEND"> <input type="reset" value="CLEAR"> </form>
Simply put, this form gets the name, email of the visitor, subject and message. Change the underlined numbers to set their sizes. You can put this on a table or use CSS formatting to make it look neater but the important thing here is not changing the names of the text boxes and the text area.
Step 3: Get The Message
Now comes the fun part. The visitor needs to fill out the form completely and give a valid email address otherwise, the message won't be sent. After the image is sent, there will be a message thanking your visitor for the email.
Ready for the code?
<?php
// GETS THE INFORMATION POSTED BY THE VISITOR
// AND REMOVES HTML TAGS FOR SECURITY
$Name = strip_tags($_POST['Name']);
$Email = strip_tags($_POST['Email']);
$Subject = strip_tags($_POST['Subject']);
$Message = strip_tags($_POST['Message']);
// CHECKS IF THE FORM WAS FILLED OUT CORRECTLY
if (!$Name || !eregi('^(.+)@(.+)\.(.+)$', $Email) || !$Subject || !$Message)
{
// ERROR MESSAGE IF THE FORM IS FILLED INCORRECTLY
echo "<>You didn't fill in all the fields. Press the back button of your browser and try again.</p>";
}
else
{
// YOUR EMAIL
$MyEmail = "you@email.com";
// SETS THE HEADERS
$Headers = "From: \"$Name\" <$Email>\n";
// SYNTAX FOR SENDING AN EMAIL
mail("$MyEmail","$Subject","$Message","$Headers");
// MESSAGE AFTER SENDING AN EMAIL
echo "<p>Thank you, $Name. Your email has been sent.</p>";
}
?>
We will name this file sendemail.php. Comments are already placed in the code to explain what they do. Just change the underlined text with your own preferences and you're all set.
Conclusion
Very useful, huh? You may download the files in this tutorial here. Enjoy!
If you have any questions or if you want to discuss this tutorial, you may post at Blinding Light MB.