« Put watermark on images using PHPMake php counter »

Make contact form and send email in PHP Posted in PHP Tutorials | 334 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 experience with millions of other webmasters visiting our website. Contact us for more information how to become a contributor.

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

test July 24, 2014 at 1:13 pm | Reply

0

iitkid3@gmail.comiitkid3@gmail.comiitkid3@gmail.comiitkid3@gmail.com
d July 23, 2014 at 2:14 pm | Reply

0

sssssssssssssssssssssssss
Brandt Fourie July 12, 2014 at 9:36 pm | Reply

0

Hi, i copied everything as per above but my php code is showing on the webpage. what am i doing wrong? Please help.
creativeyoung July 1, 2014 at 6:21 am | Reply

0

Hi, this seems like an awesome form!
Abel June 18, 2014 at 7:16 pm | Reply

0

I allready have a contact form on my website with a php file connecting to the db all of that is working but the email notification is not any help somebody????
Deepak Mishra June 6, 2014 at 11:39 am | Reply

0

i made a contact.html but when i click on submit button nothing happen so please help me when i clicked on submit button i need a message.....so pls reply as early as possible
biff June 7, 2014 at 11:19 am

0

that's because it you should save it as PHP extension
pawan May 29, 2014 at 2:51 pm | Reply

+2

forgot password send link on mail

<?php

include_once 'psl-config.php';
include_once 'functions.php';
sec_session_start();

function mail_sent()
{
$dbhost= HOST;$dbname= DATABASE;$dbuser= USER;$dbpass= PASSWORD;

if(isset($_POST['email']))
{
$mailid=filter_input(INPUT_POST, $_POST['email'], FILTER_SANITIZE_EMAIL);
$mailid= filter_var($mailid, FILTER_VALIDATE_EMAIL);
if(!filter_var($mailid, FILTER_VALIDATE_EMAIL))
{
$_SESSION['invalidmail']="<div class='alert alert-danger'>
<center><strong>The email address you entered is not valid...</strong> </center>.
</div>";


}
try{
$dbh= new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);

} catch(Exception $e){

die("Unable to connect server:" .$e->getMessage());

}
$aasql=$dbh->prepare("select email from secure_user where email = :email ");
$aasql->bindParam(':email',$_POST['email']);
$aasql->execute();
$asValue=$aasql->fetchAll();
foreach($asValue as $data)

$getmail= $data['email'];
$putmail=$_POST['email'];
if($getmail==$putmail)
{
$mailto=$putmail;
$subject="click here to Reset Password ";
$message="<html>
<head>
<title>Kcc Mail</title>
</head>
<body>
<p><a href='http://example.com/reset-password.php?emailid=pawansen9770@gmail.com'>Click here to reset password</a></p>
</body>
</html>";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: KCCL <pawan@kccl.in>' . "\r\n";

if(mail($mailto,$subject,$message,$headers))
{
$_SESSION['success']="<div class='alert success alert-success'>
<button class='close' data-dismiss='alert'></button>
<p class='col-md-offset-4'>password reset link send Check Your Mail !!!</p></div>";

header('location:../index.php');
}else
{
header('Location: ../error.php?err=email error');
}
}else{

$_SESSION['errmail']="<div class='alert alert-danger'>
<center><strong>Authentication Failed ! Please check your Email address...</strong> </center>.
</div>";

header('location:../index.php');
}



}
}
mail_sent();

?>


<form role="form" action="#" id="reset-password" method="post" name="reseat_password">

<h3 class="form-title">Reset Your Password</h3>

<div class="form-group">
<label class="control-label visible-ie8 visible-ie9">New Password</label>
<div class="input-icon">
<i class="fa fa-lock"></i>
<input class="form-control placeholder-no-fix" type="password" autocomplete="off" placeholder="new password" id="new_password" name="new_password" required/>
</div>
</div>
<div class="form-group">
<input type="hidden" class=" form-control " value="" name="p" id="p">
<input type="hidden" class=" form-control " value="<?php $email; ?>" name="email" id="email">
<label class="control-label visible-ie8 visible-ie9">Repeat Password</label>
<div class="input-icon">
<i class="fa fa-lock"></i>
<input class="form-control placeholder-no-fix" type="password" autocomplete="off" placeholder="Repeat password" id="repeat_password" name="repeat_password" required/>
</div>
</div>
<div class="form-actions">
<button type="button" id="resetPass" class="btn green pull-right">
Reset Password <i class="m-icon-swapright m-icon-white"></i>
</button>
</div>

</form>
freddyromano May 28, 2014 at 11:23 am | Reply

0

hello
Andrei May 22, 2014 at 2:30 am | Reply

+2


<html>
<body>

<?php
if (isset($_POST['email']))
// Check if form is completed
{
// Getting varables
$expeditorEmail = $_POST['email'] ;
$subiect = $_POST['subject'] ;
$mesaj = $_POST['message'] ;

$destinatarEmail="webmaster@website.com";


if (mail(
$destinatarEmail,
"Subject: $subiect",
$message, "From: $expeditorEmail")

)

{
echo "Succes. Message was send!";
}
else
{
echo "Error. Message not send!";
}

}
else
// If this camp it's null... we show this form
{
echo "<form method='post' action='mailForm.php'>
Email: <input name='email' type='text' /><br />
Subject: <input name='subject' type='text' /><br />
Message:<br />
<textarea name='message' rows='15' cols='40'>
</textarea><br />
<input type='submit' />
</form>";
}
?>

</body>
</html>
Ole Remi May 10, 2014 at 12:36 am | Reply

+1

Hi Why is it not working!!!! :(


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 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 ~