Send contents of contact form direct to email via php [duplicate] - javascript

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 6 years ago.
I have a contact form on my wordpress site but I cannot get information from the form to send to my email address when the submit button is clicked.
Once the submit button has been clicked and the email has been sent I would like a confirmation to appear underneath the submit button that the message has been sent/error if it hasn't. Note: I will update the css for the contact form to accommodate the extra text.
This is my form code:
<form action="secure_email.php" method="post" id="contact-form-content">
<h5>You have had a look, so let's get cracking. Email me at me#myemail.com or use this nifty thing.</h5><br></br>
<legend>Contact Form</legend>
<input type="text" placeholder="Full Name" name="full-name" id="full-name" required;><br></br>
<input type="text" placeholder="Email" name="email" id="email" required;><br></br>
<textarea placeholder="Message" name="message" id="message" rows="100" cols="100" wrap="hard" required;></textarea><br></br>
<button type="submit" name="submit" value="submit">Send</button>
</form>
And this is secure_email.php file:
<?php
if(isset($_POST['submit'])){
$to = "me#myemail.com"; // this is your Email address
$email = $_POST['email']; // this is the sender's Email address
$full-name = $_POST['full-name'];
$subject = "Form submission";
$message = $full-name . " " . $email . " wrote the following:" . "\n\n" . $_POST['message'];
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to, $subject, $message, $headers);
if (isset($_POST['submit']))
{
if (mail($to, $subject, $message, $headers))
echo "Thank you for contacting me!";
}
else
{
echo '<p>Something went wrong, go back and try again!</p>';
}
}
?>
Just to update all this is the working code with contact form details being sent to my given email, the confirmation message appearing within the contact form and scroll back to contact form to see the confirmation message
<div id="contact-form">
<form action="#contact" method="post" id="contact-form-content">
<h5>You have had a look, so let's get cracking. Email me at me#myemail.com or use this nifty thing.</h5><br></br>
<legend>Contact Form</legend>
<input type="text" placeholder="Full Name" name="fullname" id="fullname" required;><br></br>
<input type="text" placeholder="Email" name="email" id="email" required;><br></br>
<textarea placeholder="Message" name="message" id="message" rows="100" cols="100" wrap="hard" required;></textarea><br></br>
<button type="submit" name="submit" value="submit">Send</button>
<?php
if(isset($_POST['submit'])){
$to = "me#myemail.com"; // this is your Email address
$email = $_POST['email']; // this is the sender's Email address
$fullname = $_POST['fullname'];
$subject = "Form submission";
$message = $fullname . " " . $email . " wrote the following:" . "\n\n" . $_POST['message'];
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
if (mail($to, $subject, $message, $headers)){
echo "Thank you for contacting me!";
}
else
{
echo '<p>Something went wrong, go back and try again!</p>';
}
}
?>
</form>
</div>
</div>

Please use mail functions.
PHP Mail Function
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($to, $subject, $message, $headers);
WordPress Mail Function
wp_mail($to, $subject, $message, $headers);

You eitherneed to
use Ajax to post your form data to secure-email.php then add the success message on succes in JavaScript.
Or
Post to the same page as the form, detect if the form has been submitted and send your email, then echo your success message if the mail sends successfully. The page will refresh when they hit submit and the message will be displayed.

Related

Contact Form Posting

I have created a html, php and js files for my Contact Form.
I upload it to my Hosting Provider just for testing as I don't have a live server.
When I fill out all required fields and hit Submit, I don't get information send to email address.
This is just a simple form so that customers can send me their query and details.
$(function() {
$(".form-control").on('focus', function() {
$(this).parents(".form-group").addClass('focused');
});
$(".form-control").on('blur', function() {
$(this).parents(".form-group").removeClass('focused');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="container">
<form action="form-handler.php" method="POST" class="form">
<div class="form-group">
<label for="name" class="form-label">Your Name</label>
<input type="text" class="form-control" id="name" name="Name" placeholder="Jane Doe" tabindex="1" required>
</div>
<div class="form-group">
<label for="email" class="form-label">Your Email</label>
<input type="text" class="form-control" id="email" name="Email" placeholder="Jane#Doe.com" tabindex="2" required>
</div>
<div class="form-group">
<label for="subject" class="form-label">Subject</label>
<input type="text" class="form-control" id="subject" name="Subject" placeholder="Subject" tabindex="3" required>
</div>
<div class="form-group">
<label for="message" class="form-label">Message</label>
<textarea class="form-control" name="message" id="message" cols="50" rows="5" placeholder="Write your message here..." tabindex="4"></textarea>
</div>
<div>
<button class="btn" type="submit">Send Message</button>
</div>
</form>
</div>
</body>
</html>
PHP
<?php
$message_sent = false;
if (isset($_POST['email']) && $_POST['email'] != '')
{
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
//submit the form
$userName = $_POST['name'];
$userEmail = $_POST['email'];
$messageSubject = $_POST['subject'];
$message = $_POST['message'];
$to = "...#....com";
$body = "";
$body = "From:" . $userName . "\r\n";
$body = "Email:" . $userEmail . "\r\n";
$body = "Message:" . $message . "\r\n";
mail($to, $messageSubject, $body);
$message_sent = true;
}
}
?>
Your code is
$body = "From:" . $userName . "\r\n";
$body = "Email:" . $userEmail . "\r\n";
$body = "Message:" . $message . "\r\n";
mail($to, $messageSubject, $body);
And from documentation I saw that a correct way to send additional headers like FROM is the folloewing:
$to = 'nobody#example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
Another more complete way is the following:
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = 'To: Mary <mary#example.com>, Kelly <kelly#example.com>';
$headers[] = 'From: Birthday Reminder <birthday#example.com>';
$headers[] = 'Cc: birthdayarchive#example.com';
$headers[] = 'Bcc: birthdaycheck#example.com';
// Mail it
mail($to, $subject, $message, implode("\r\n", $headers));
Finally, .. instead of code this:
mail($to, $messageSubject, $body);
$message_sent = true;
You should code this
$message_sent = mail($to, $messageSubject, $body);
Because your code assumes all works fine but mail function already return true or false if mail is sent or not.
But the most important stuff I saw is that your form ha inputs named:
Name
Email
Subject
message
and your php code check for
$_POST['name']; // different from Name
$_POST['email']; // different from Email
$_POST['subject']; // different rom Subject
$_POST['message']; // ok
So, ... if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) should always return false because $_POST['email'] email not exists.

How to show success message below html form after form submit which is being handled by different php file

There is a form in my index.php file. This form is handling from a different php file named send-mail.php. I want to show a message inside alert div in index.php file. Can this be done by php or javascript will be needed too?
index.php:
<section id="contact">
<form action="send-mail.php" id="form" method="post" name="form">
<input id="name" name="name" placeholder="your name" type="text" required>
<input id="email" name="email" placeholder="your e-mail" type="email" required>
<textarea cols="50" id="message" name="message" placeholder="your enquiry" rows="4" required></textarea>
<input type="submit" name="submit" id="submit" value="Send Message">
</form>
<div class="alert alert-dismissible fade in hide" role=alert>
<button type=button class=close data-dismiss=alert aria-label=Close><span aria-hidden=true>×</span></button>
</div>
</section>
send-mail.php:
<?php
if(isset($_POST['submit'])){
// Get the submitted form data
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
// Recipient email
$toEmail = 'user#example.com';
$emailSubject = 'Contact Request Submitted by '.$name;
$htmlContent = '<h2>Contact Request Submitted</h2>
<h4>Name</h4><p>'.$name.'</p>
<h4>Email</h4><p>'.$email.'</p>
<h4>Message</h4><p>'.$message.'</p>';
// Set content-type header for sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Additional headers
$headers .= 'From: '.$name.'<'.$email.'>'. "\r\n";
// Send email
if(mail($toEmail,$emailSubject,$htmlContent,$headers)){
$statusMsg = 'Your contact request has been submitted successfully !';
$msgClass = 'alert-success';
header('location: index.php#contact');
}else{
$statusMsg = 'Your contact request submission failed, please try again.';
$msgClass = 'alert-danger';
header('location: index.php#contact');
}
}
?>
Change your redirects to:
header('location: index.php?result='.$msgClass.'#contact');
Then adding the following to your index.php file:
if ($_GET['result']=="alert-success") {
// display success message here
} elseif ($_GET['result']=="alert-danger") {
// display error message here
}

php form only sending blank emails

Hi there I am having some trouble getting my php form to actually forward the information that is put in.
I have been struggling for a couple of days now and researched a lot online but unfortunately haven't found the answer.
The form works and redirects with a success message, is sent to my websites email then forwarded to a personal email. This is all instant but I only seem to receive blank emails.
Here is the php code:
<?php
$from = "admin#abievetattoo.com";
$to = "abievetattoo#gmail.com";
$subject = "Booking Enquiry";
$cf_name = Trim(stripslashes($_POST['cf_name']));
$cf_email = Trim(stripslashes($_POST['cf_email']));
$cf_message = Trim(stripslashes($_POST['cf_message']));
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
$Body = 'MIME-Version: 1.0' . "\r\n";
$Body .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$Body .= 'From: '. $from . "\r\n" . 'X-Mailer: PHP/' . phpversion();
$Body = "";
$Body = "Name: ";
$Body = $cf_name;
$Body = "\n";
$Body = "eMail: ";
$Body = $cf_email;
$Body = "\n";
$Body = "Message: ";
$Body = $cf_message;
$Body = "\n";
$success = mail($to, $subject, $Body, "From: $from" . "\r\n");
?>
<script type="text/javascript">
alert("Thank you for the message. Abi will respond shortly.");
window.location = 'http://abievetattoo.com/contact.html';
</script>
Here is the html code:
<form action="contact.php" method="post">
<p>Your name</p>
<input type="text" name="cf_name" required>
<br>
<p>Your e-mail</p>
<input type="email" name="cf_email" required>
<br>
<p>Message</p>
<input type="text" name="cf_message">
<br><br>
<input type="submit" value="Send">
<input type="reset" value="Clear">
</form>
Any help would be very much appreciated, thanks.

add email validation prior to submitting on php form

I have the following simple form that I am trying to get the email validation error to
show up within the form to show the error prior to submitting.
Is there a way to do this with PHP or do I have to use JSON?
If I have to use JSON, can anyone show me how to do this?
Thanks in advance.
form.html:
<form method="post" name="form" action="form.php">
<p>Robot: <input type="text" name="robot" ></p>
<p>Name: <input type="text" name="name" ></p>
<p>Email: <input type="email" name="email"></p>
<p>Phone: <input type="telephone" name="phone"></p>
<p>Message: <textarea name="message"></textarea></p>
<p><input type="submit" value="Send Form"></p>
</form>
<div id="error"></div>
form.php
<?php
// send to and from
$to = "email#example.com";
$headers = "From: email#example.com \r\n";
$headers .= "Reply-To: email#example.com \r\n";
// form inputs
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$robot = $_POST['robot'];
// email message
$email_subject = "Web Contact Message";
$email_body =
"A message from your website contact form \n\n".
"Email: $email \n\n".
"Phone: $phone \n\n".
"From: $name \n\n".
"Message: \n".
"$message \n";
// honeypot
if($robot)
header( "Location: http://www.example.com/nothankyou.html" );
else{
//validate email
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo '<div id="error">Please Enter a Valid Email</div>';
}
else
{
// send it
mail($to,$email_subject,$email_body,$headers);
header( "Location: http://www.example.com/thankyou.html" );
}
}
?>
You could try using a javascript/jquery plugin to do your front end validation (ex. http://jqueryvalidation.org/, http://bootstrapvalidator.com/). If you still wanted to keep your existing code I'd suggest something like:
First, merge your form.html to form.php
Make sure your php mailing code stays at the top of the file because php headers cannot have any output done before calling them.
<?php
if (count($_POST)) {
// send to and from
$to = "email#example.com";
$headers = "From: email#example.com \r\n";
$headers .= "Reply-To: email#example.com \r\n";
// form inputs
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$robot = $_POST['robot'];
// email message
$email_subject = "Web Contact Message";
$email_body = "A message from your website contact form \n\n" .
"Email: $email \n\n" .
"Phone: $phone \n\n" .
"From: $name \n\n" .
"Message: \n" .
"$message \n";
// honeypot
if ($robot)
header("Location: http://www.example.com/nothankyou.html");
else {
//validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: form.php?error=email_error");
} else {
// send it
mail($to, $email_subject, $email_body, $headers);
header("Location: http://www.example.com/thankyou.html");
}
}
}
?>
<form method="post" name="form" action="">
<p>Robot: <input type="text" name="robot" ></p>
<p>Name: <input type="text" name="name" ></p>
<p>Email: <input type="email" name="email"></p>
<p>Phone: <input type="telephone" name="phone"></p>
<p>Message: <textarea name="message"></textarea></p>
<p><input type="submit" value="Send Form"></p>
</form>
<?php
if (isset($_GET["error"]) && $_GET["error"] == "email_error") {
?>
<div id="error">Please Enter a Valid Email</div>
<?php
}

Incorrect function on php script

I have a simple contact form I'm trying to implement but I'm getting an "incorrect function" error when I try to launch it. My code below is as follows, and when I click submit, it redirects to
http://mywebsite.com/contactme.php
but with the text "Incorrect function" and that's it. My debug on firefox shows the following error:
POST http://www.mywebsite.com/v/vspfiles/contactform/contactme.php [HTTP/1.1 405 Method Not Allowed 33ms]
13:54:52.368 The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range.
The character encoding of the page must be declared in the document or in the transfer protocol.
I am using volusion software if that helps. But I have no idea if the error is in my code or because my webhost won't allow the function. Can someone give me some insight? I have tried the "contactme.php" page with and without the doctype declared. My two files are below. I do not have an "error.htm" page.
contact.html:
<!DOCTYPE html>
<html>
<head>
<title>Contact</title>
</head>
<body >
<div id="contact-area">
<form method="post" action="/v/vspfiles/contactform/contactme.php">
<h3>Contact us</h3>
<label for="Name">Name:</label>
<input type="text" name="Name" id="Name" />
<label for="City">City:</label>
<input type="text" name="City" id="City" />
<label for="Email">Email:</label>
<input type="text" name="Email" id="Email" />
<label for="Message">Message:</label><br />
<textarea name="Message" rows="20" cols="20" id="Message"></textarea>
<input type="submit" name="submit" value="Submit" class="submit-button" />
</form>
<div style="clear: both;"></div>
</div>
</body>
</html>
contactme.php:
<?php
$EmailFrom = "email#gmail.com";
$EmailTo = "email#gmail.com";
$Subject = "contact form";
$Name = Trim(stripslashes($_POST['Name']));
$Tel = Trim(stripslashes($_POST['Tel']));
$Email = Trim(stripslashes($_POST['Email']));
$Message = Trim(stripslashes($_POST['Message']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Tel: ";
$Body .= $Tel;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// informs user they submitted, redirects to homepage
if ($success){
alert("Thank you for your interest in our multiple sample processing system. A member of the Claremont Bio team will respond to you shortly.");
window.location.assign(location.hostname);
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>
alert("Thank you for your interest in our multiple sample processing system. A member of the Claremont Bio team will respond to you shortly.");
window.location.assign(location.hostname);
This is not valid php code, it is javascript. It definitely should not be in your php script.
As an alternative, in your if($success) condition you could redirect to a "success.php" page. For example:
if($success){
header("Location: http://www.mydomain.com/success.php");
}
An example of a contact.php page I use is as follows, note as per Jorge's comments, I make use of echoing the command...
<?php
// configuration
require("../includes/config.php");
// if form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// submission is sanitised using the "query" function
$name = check_input($_POST["name"]);
$email = check_input($_POST["email"]);
$phone = check_input($_POST["phone"]);
$message = check_input($_POST["message"]);
$category = $_POST["category"];
switch($category)
{
// do some checking here
}
// insert user into db
// Success Message
$success = "
<div class=\"row-fluid\">
<div class=\"span11\">
<div class=\"alert alert-block alert-success\" id=\"thanks\">
<h4>Got it!</h4>
<br/>
<p>I'll be in touch within 24 hours. <strong> Promise.</strong></p>
<br/>
<p>In the meantime, why not check out my Facebook page...</p>
<br/>
www.facebook.com/myfacebooksite
</div>
</div>
</div>
";
$subject = 'New Website Message!';
$mailto = 'your#email.com';
// HTML for email to send submission details
$body = "
<br>
<p>The following information was submitted through the contact form on your website:</p>
<p><b>Name</b>: $name<br>
<b>Email</b>: $email<br>
<b>Phone</b>: $phone<br>
<b>Category</b>: $category<br>
<b>Message:</b>: $message<br>
";
$headers = "From: $name <$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";
$mailtext = "<html><body>$body</body></html>";
if (mail($mailto, $subject, $mailtext, $headers)) {
echo "$success"; // success
}
else
{
echo 'Form submission failed. Please try again...'; // failure
}
}
else
{
// else render form
redirect("/index.html");
}
?>
edit:
my contact form page has the following js:
// do the mailing
$('#contact_form').on('submit', function(e) {
e.preventDefault(); //Prevents default submit
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
$.ajax({
type: 'POST',
url: 'contact.php',
data: post_data,
success: function(msg) {
$(form).fadeOut(200, function(){
form.html(msg).fadeIn();
});
}
});
});
Hope that helps steer you...
So turns out this isn't my error, this is my webhost. Had to call them up and they told me they don't support PHP currently. so I'm off to rewrite this is javascript. I'll give the answer to Jason as his was the most technically correct and pointed out the error. Thanks guys.

Categories