« Put watermark on images using PHPMake php counter »

Make contact form and send email in PHP Posted in PHP Tutorials | 324 Comments
Having a contact form on your web site is vital when you need to know what your site visitors think about your web site. We will first create a simple contact form with 3 fields - Email address, Name, Comments. I will use a table to align the 3 fields and the Send button. Create a new file and paste the code below in it. Save it as test.php and upload it to your web server. Now, you have a web page (http://www.yourdomain.com/test.php) with a simple contact form on it.

<form action="test.php" method="post"> 
<table width="400" border="0" cellspacing="2" cellpadding="0">
<tr>
<td width="29%" class="bodytext">Your name:</td>
<td width="71%"><input name="name" type="text" id="name" size="32"></td>
</tr>
<tr>
<td class="bodytext">Email address:</td>
<td><input name="email" type="text" id="email" size="32"></td>
</tr>
<tr>
<td class="bodytext">Comment:</td>
<td><textarea name="comment" cols="45" rows="6" id="comment" class="bodytext"></textarea></td>
</tr>
<tr>
<td class="bodytext"> </td>
<td align="left" valign="top"><input type="submit" name="Submit" value="Send"></td>
</tr>
</table>
</form>


Then we will need the actual PHP code which will send the email when the above form is submitted. We will need to define the email that the message should be sent to ($ToEmail) and also the subject for the message that will be sent ($EmailSubject). Change youremail@site.com to your email address where the message should be sent and also add an appropriate subject for you message. The $mailheader variable is used to define the email message header. We set the From, Reply-To and Content-type fields for the message. There are some more fields that can be used but for this example we will only use these 3. Depending on your server configuration you may need to have the From and Reply-to fields be a valid email address from your server.If you have a domain name mysite.com, then you should use a valid email address such as contact@mysite.com. In this example I am sending the email using the actual email address that is submitted via the form on site. Next all the data submitted via the web form is taken from the $_POST variable and saved in the $MESSAGE_BODY variable. Using the nl2br function you will make all the new lines in your comments box appear as new lines in your email message too. Having all the needed data for our email message we will use the mail() function which will send that email for us.

<?php 
$ToEmail = 'youremail@site.com';
$EmailSubject = 'Site contact form';
$mailheader = "From: ".$_POST["email"]."\r\n";
$mailheader .= "Reply-To: ".$_POST["email"]."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
$MESSAGE_BODY = "Name: ".$_POST["name"]."<br />";
$MESSAGE_BODY .= "Email: ".$_POST["email"]."<br />";
$MESSAGE_BODY .= "Comment: ".nl2br($_POST["comment"])."<br />";
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
?>


All we have to do now is to combine the web form and email sending code into a single page. We will use an IF statement to check if the form has been submitted and if so it will send that email and will show a "Your message was sent" message on the screen instead of the web form.

<?php 
if ($_POST["email"]<>'') {
$ToEmail = 'youremail@site.com';
$EmailSubject = 'Site contact form';
$mailheader = "From: ".$_POST["email"]."\r\n";
$mailheader .= "Reply-To: ".$_POST["email"]."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
$MESSAGE_BODY = "Name: ".$_POST["name"]."<br />";
$MESSAGE_BODY .= "Email: ".$_POST["email"]."<br />";
$MESSAGE_BODY .= "Comment: ".nl2br($_POST["comment"])."<br />";
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
?>
Your message was sent
<?php
} else {
?>
<form action="test.php" method="post">
<table width="400" border="0" cellspacing="2" cellpadding="0">
<tr>
<td width="29%" class="bodytext">Your name:</td>
<td width="71%"><input name="name" type="text" id="name" size="32"></td>
</tr>
<tr>
<td class="bodytext">Email address:</td>
<td><input name="email" type="text" id="email" size="32"></td>
</tr>
<tr>
<td class="bodytext">Comment:</td>
<td><textarea name="comment" cols="45" rows="6" id="comment" class="bodytext"></textarea></td>
</tr>
<tr>
<td class="bodytext"> </td>
<td align="left" valign="top"><input type="submit" name="Submit" value="Send"></td>
</tr>
</table>
</form>
<?php
};
?>

Do you know PHP / HTML / CSS / JS well?

Write tutorial on a topic you are good in and become a trusted PHP jabber! Share your knowledge with thousands of webmasters and we will reward you for your generosity by giving you bonus points which you can use as a voucher to buy any of our commercial products. Read more about our reward program.

324 Replies to "Make contact form and send email in PHP"

surbhi April 18, 2014 at 3:00 pm | Reply

0

fhgfhghgh
acantjong April 17, 2014 at 10:15 pm | Reply

0

This form i use, and working good. http://www.freecontactform.com/email_form.php
bala March 26, 2014 at 9:59 am | Reply

0

host name wrong send mail
wayne seabright February 22, 2014 at 10:17 am | Reply

+1

If I wanted to add 2 more
$message_body
, 
and have it sent to my email how would I do it?
Spencer Phillips January 2, 2014 at 9:16 pm | Reply

+1

I am using codeigniter/twitter bootstrap and I dont know where to put these files. Can you please help?
Jesse December 24, 2013 at 9:52 am | Reply

+10

This form script is open to header injection exploits. I suggest trying http://formtoemail.com for a simpler more secure solution.
boyan November 16, 2013 at 5:29 am | Reply

+3

good Contact Form. All Work Nice.
Muhammad Usman November 11, 2013 at 12:07 pm | Reply

+8

Easy code contact form using php with form validation.
Create mail.php file and copy past this code mail.php file.

<?php
if ($_POST['parse_var'] == "Mail"){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

// Check form validation
if ((!$name) || (!$email) || (!$message)){
// Header Message
$errorMsg = 'ERROR: You did not submit the following required information:<br />';
// Check name
if(!$name){
$errorMsgname .= 'style="border: 1px solid #FF0000; padding-left: 4px; padding-right: 4px; padding-top: 1px; padding-bottom: 1px"';
}
// Check email
if(!$email){
$errorMsgemail .= 'style="border: 1px solid #FF0000; padding-left: 4px; padding-right: 4px; padding-top: 1px; padding-bottom: 1px"';
}
if(!$message){
$errorMsgmessage .= 'style="border: 1px solid #FF0000; padding-left: 4px; padding-right: 4px; padding-top: 1px; padding-bottom: 1px"';
}
// Check email validation
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$errorMsgeinvalidemail .= 'style="border: 1px solid #FF0000; padding-left: 4px; padding-right: 4px; padding-top: 1px; padding-bottom: 1px"';
}
}else{



$body = <<<EOD
<br><hr><br>
$message
EOD;

//Email to

$to = "you@yourdomain.com";// Change with your email address.

//Email Subject
$subject = "Test Email";// Change with your email subject.

$headers = "From: $email\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$success = mail("$to", "$subject", "$body", "$headers");


if ($success == true){
?>
<script language="javascript" type="text/javascript">
alert('Thank you for the contact us. We will back to you shorrtly.');
window.location = "mail.php";
</script>
<?php
}else{
?>
<script language="javascript" type="text/javascript">
alert('Message not sent. Please, send us email on "info@visacardbitcoin.com"');
window.location = "mail.php";
</script>
<?php
} } }
?>


<html><head>
</head>
<body>
<?php print "$errorMsg";?>
<form name="form1" action="mail.php" method="POST">
<input type="hidden" name="parse_var" value="Mail">
Name: <input type="text" name="name" value="<?php print "$name";?>" <?php print "$errorMsgname";?>><br>
email: <input type="text" name="email" value="<?php print "$email";?>" <?php print "$errorMsgemail";?><?php print "$errorMsgeinvalidemail";?>><br>
message: <textarea name="message" <?php print "$errorMsgmessage";?>><?php print "$message";?></textarea><br>
<input type="submit" value="Submit" name="B1">
</body>
</html>
olof October 24, 2013 at 8:41 pm | Reply

+6

A word of security: I can't see that this code escapes the input data.
zuby October 18, 2013 at 3:38 pm | Reply

+3

kindly tell me what is worng mail not working with js validation
here is html

<form action="mail.php" method="POST">
<p>Name</p> <input type="text" name="name">
<p>Email</p> <input type="text" name="email">
<p>Message</p><textarea name="message" rows="6" cols="25"></textarea><br />
<input type="submit" value="Send"><input type="reset" value="Clear">
</form>


here is php

<?php $name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$formcontent="From: $name \n Message: $message";
$recipient = "emailaddress@here.com<script type="text/javascript">
/* <![CDATA[ */
(function(){try{var s,a,i,j,r,c,l,b=document.getElementsByTagName("script");l=b[b.length-1].previousSibling;a=l.getAttribute('data-cfemail');if(a){s='';r=parseInt(a.substr(0,2),16);for(j=2;a.length-j;j+=2){c=parseInt(a.substr(j,2),16)^r;s+=String.fromCharCode(c);}s=document.createTextNode(s);l.parentNode.replaceChild(s,l);}}catch(e){}})();
/* ]]> */
</script>";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
echo "Thank You!";
?>


Please be polite and helpful and do not spam or offend others. We promise you will be treated the same way.

Log in your free account or if you still haven't joined our Webmaster Community Reward Program, you can create your free account now.

Posting tip:
if you use code in your comments please put it in these tags [php], [sql], [css], [js]
PHP code example: [php] echo date("Y-m-d"); [/php]

Thank you,
~ PHPJabbers team ~