I have a contact form that I manage to make work.
The form has some fields, the reCaptcha and a consent check box.
The PHP code is like this:
if($_POST)
{
$to_Email = "contact#blabla.com"; //Replace with recipient email address
$subject = 'Form contact'; //Subject line for emails
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
//check $_POST vars are set, exit if any missing
if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userMessage"]) || !isset($_POST["userprivacy"]))
{
$output = json_encode(array('type'=>'error', 'text' => 'It is necessary to fill in all the fields and validate the terms and conditions box.'));
die($output);
}
//Sanitize input data using PHP filter_var().
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_Subject = $_POST["userSubject"];
$user_Message = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);
$customer_privacy = filter_var($_POST["userprivacy"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($user_Name)<3) // If length is less than 3 it will throw an HTTP error.
{
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
$output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
die($output);
}
if(strlen($user_Message)<5) //check emtpy message
{
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
$message_Body = "<strong>Name: </strong>". $user_Name ."<br>";
$message_Body .= "<strong>Email: </strong>". $user_Email ."<br>";
$message_Body .= "<strong>Empresa: </strong>". $user_Subject ."<br>";
$message_Body .= "<strong>Message: </strong>". $user_Message ."<br>";
$message_Body .= "<strong>Message: </strong>". $customer_privacy ."<br>";
$headers = "From: " . strip_tags($user_Email) . "\r\n";
$headers .= "Reply-To: ". strip_tags($user_Email) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
//proceed with PHP email.
/*$headers = 'From: '.$user_Email.'' . "\r\n" .
'Reply-To: '.$user_Email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
*/
$sentMail = #mail($to_Email, $subject, $message_Body, $headers);
if(!$sentMail)
{
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hola '.$user_Name .' Gracias por contactanos, en breve nos pondremos en contacto contigo.'));
die($output);
}
}
And the HTML like this:
<form class="getin_form wow fadeInUp">
<div class="col-sm-12" id="result"></div>
<div class="row">
<div class="col-md-12 col-sm-12">
<div class="form-group bottom45">
<input class="form-control" type="text" placeholder="Nombre" name="user_name" required>
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group bottom45">
<input class="form-control" type="email" name="user_email" placeholder="Correo Eletronico" required>
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group bottom45">
<input class="form-control" type="text" name="last_name" placeholder="Empresa">
</div>
</div>
<div class="col-md-12 col-sm-12">
<div class="form-group bottom45">
<textarea class="form-control" name="user_message" placeholder="Mensaje"></textarea>
</div>
<div class="col-md-12 col-sm-12">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<form action="?" method="POST">
<div class="g-recaptcha" data-sitekey="aaaaaaaaaaaaaaaaaaaaaaaaaaa"></div>
</div>
<div>
<div class="col-md-1 checker" id="uniform-customer_privacy">
<input type="checkbox" value="0" required name="customer_privacy" autocomplete="off">
</div>
<div><span>He leído y acepto los <span style="text-decoration: underline;"><strong>Términos y condiciones</strong></span> de blablabla.</span></div>
</div>
<div class="col-sm-12">
<button type="button" class="button defaulthole" id="submit_btn">Enviar</button>
</div>
</div>
</form>
When I fill out the form and press send, I still get the error that it is not completed.
I don't know if I'm putting any variables wrong - I don't really understand why it's not working.
Related
My server receives emails but none of the fields are shown.
All fields are empty in the email? Do you have any suggestions? I have tried everything that I know but no results. Form fields does not pass to the php
<?php
// variables start
$name = "";
$email = "";
$message = "";
$name = trim($_POST['contactNameField']);
$email = trim($_POST['contactEmailField']);
$message = trim($_POST['contactMessageTextarea']);
// variables end
// email address starts
$emailAddress = 'mail#domain.com';
// email address ends
$subject = "Message From: $name";
$message = "<strong>From:</strong> $name <br/><br/> <strong>Message:</strong> $message";
$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";
//send email function starts
mail($emailAddress, $subject, $message, $headers);
//send email function ends
?>
for this form
<form action="php/contact.php" method="post" class="contactForm" id="contactForm">
<div class="form-field form-name">
<label class="contactNameField color-theme" >Name:<span>(required)</span></label>
<input type="text" name="contactNameField" id="contactNameField" />
</div>
<div class="form-field form-email">
<label class="contactEmailField color-theme" >Email:<span>(required)</span></label>
<input type="text" name="contactEmailField" id="contactEmailField" />
</div>
<div class="form-field form-text">
<label class="contactMessageTextarea color-theme" >Message:<span>(required)</span></label>
<textarea name="contactMessageTextarea" id="contactMessageTextarea"></textarea>
</div>
<div class="form-button">
<input type="submit" class="btn bg-highlight text-uppercase font-900 btn-m btn-full rounded-sm shadow-xl contactSubmitButton" value="Gönder" />
</div>
Thank you
I have an HTML form where you can enter your email and a message.
After you submit this form i would like an email to be sent to my email (fixed) and to the email that is filled in trough the form.
I got my email to work but i can't seem to get the email from my HTML form into the send list in PHP. Any suggestions?
Code (html):
<form id="contact-form" method="post" action="js/contact.php" role="form">
<div class="messages"></div>
<div class="controls">
<div class="row">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="form_email">Email</label>
<input id="form_email" type="email" name="email" class="form-control" placeholder="Vul hier je email adres in" required="required" data-error="Valid email is required.">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="form_message">message</label>
<textarea id="form_message" name="message" class="form-control" placeholder="Vul hier een eventuele opmerking of message in." rows="4" required="required" data-error="Please,leave us a message."></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-12">
<input type="submit" class="btn btn-success btn-send" value="Versturen">
</div>
</div>
</div>
</form>
Code PHP:
<?php
$from = 'info#mywebsite';
$sendTo = 'myemail#gmail.com'; //Here the email from the form should be added
$subject = 'Nieuwe reservering';
$fields = array('kosten' => 'kosten' , 'name' => 'Naam', 'surname' => 'Achternaam', 'phone' => 'Telefoonnummer', 'kamer' => 'Kamer', 'aankomst' => 'aankomst', 'vertrek' => 'vertrek', 'email' => 'Email', 'message' => 'Bericht');
$okMessage = 'Je bericht is verzonden!';
$errorMessage = 'Oei er ging iets fout, geeft niks. Probeer het later opnieuw.';
error_reporting(E_ALL & ~E_NOTICE);
try {
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailText ="<table>";
$emailText .="<p>Bedankt voor uw reservering, hieronder de ingevulde info:</p><br><br>";
foreach ($_POST as $key => $value) {
if (isset($fields[$key])) {
$emailText .= "<tr><td>{$fields[$key]}</td>";
$emailText .= "<td>$value</td></tr>";
}
}
$emailText .="<br><br><p>Voor vragen of wijzigingen mail naar: info#bmyemail</p>";
$emailText .="</tr></table>";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers = array('Content-type:text/html;charset=UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e){
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
} else {
echo $responseArray['message'];
}
You can specify all recipients like this: (check official guideline here)
$sendTo = 'myemail#gmail.com, abc#example.com, xyz#example.com'; // note the comma
//actual message
$message = "Message Content";
mail($sendTo, $subject, $message));
Hope it helps! :)
After your email is done, you just need to send it twice :
<?php
mail($addr1, $subject, $message, $header);
mail($addr2, $subject, $message, $header);
?>
You can also concatenate differents addresses (I've managed to send a mail to different addresses by changing my input to a textarea and writing one address per line).
Good luck!
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
I was working on my own vCard/resume website.
But I am having some trouble with my .php file and contact form.
I tried to debug it but I had no success.
Here is my form in html
<!-- form -->
<form name="contactForm" id="contactForm" method="post" action="inc/sendEmail.php">
<fieldset>
<div class="form-field">
<input name="contactName" type="text" id="contactName" placeholder="Name" value="" minlength="2" required>
</div>
<div class="form-field">
<input name="contactEmail" type="email" id="contactEmail" placeholder="Email" value="" required>
</div>
<div class="form-field">
<input name="contactSubject" type="text" id="contactSubject" placeholder="Subject" value="">
</div>
<div class="form-field">
<textarea name="contactMessage" id="contactMessage" placeholder="Message" rows="10" cols="50" required></textarea>
</div>
<div class="form-field">
<button class="submitform">Submit</button>
<div id="submit-loader">
<div class="text-loader">
Sending...
</div>
<div class="s-loader">
<div class="bounce1">
</div>
<div class="bounce2">
</div>
<div class="bounce3">
</div>
</div>
</div>
</div>
</fieldset>
</form>
<!-- Form End -->
And my php file
<?php
// Replace this with your own email address
$siteOwnersEmail = 'someone#example.com';
if($_POST) {
$name = trim(stripslashes($_POST['contactName']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$contact_message = trim(stripslashes($_POST['contactMessage']));
// Check Name
if (strlen($name) < 2) {
$error['name'] = "Please enter your name.";
}
// Check Email
if (!preg_match('/^[a-z0-9&\'\.\-_\+]+#[a-z0-9\-]+\.([a-z0-9\-]+\.)*+[a-z]{2}/is', $email)) {
$error['email'] = "Please enter a valid email address.";
}
// Check Message
if (strlen($contact_message) < 15) {
$error['message'] = "Please enter your message. It should have at least 15 characters.";
}
// Subject
if ($subject == '') { $subject = "Contact Form Submission"; }
// Set Message
$message .= "Email from: " . $name . "<br />";
$message .= "Email address: " . $email . "<br />";
$message .= "Message: <br />";
$message .= $contact_message;
$message .= "<br /> ----- <br /> This email was sent from your site's contact form. <br />";
// Set From: header
$from = $name . " <" . $email . ">";
// Email Headers
$headers = "From: " . $from . "\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";
if (!$error) {
ini_set("sendmail_from", $siteOwnersEmail); // for windows server
$mail = mail($siteOwnersEmail, $subject, $message, $headers);
if ($mail) { echo "OK"; }
else { echo "Something went wrong. Please try again."; }
} # end if - no validation error
else {
$response = (isset($error['name'])) ? $error['name'] . "<br /> \n" : null;
$response .= (isset($error['email'])) ? $error['email'] . "<br /> \n" : null;
$response .= (isset($error['message'])) ? $error['message'] . "<br />" : null;
echo $response;
} # end if - there was a validation error
}
?>
Can someone tell me what I am doing wrong here, because it isn't sending any emails.
Please try this
<?php
$message ="";
if(isset($_POST)){
mail(to,subject,message,headers,parameters);
}
?>
You have to declare type of button type="submit" OR type="button"
in this case work with form so you have to add type="submit"
and check user click button or direct access of file you can check !empty($_POST) with if
// Change in your HTML
<button class="submitform">Submit</button>
// to
<button type="submit" class="submitform">Submit</button>
//Change in your PHP
if($_POST)
// to
if(!empty($_POST))
Im trying to send an e-mail with the following script I've made. But seem to encounter a weird problem that I need help with.
The mail script
// Get field values.
$name = strip_tags($_POST["name"]);
$email = strip_tags($_POST["email"]);
$message = $_POST["msg"];
// Check if e-mail address is valid.
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set e-mail and subject.
$to = "mail#mydomain.dk";
$subject = "You have a new message.";
// Set header values.
$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";
// Set request body.
$message = "<html>";
$message .= "<body>";
$message .= "<p><b>From:</b><br>" . $name . "</p>";
$message .= "<p><b>Email:</b><br>" . $email . "</p>";
$message .= "<p><b>Message:</b><br>" . $message . "</p>";
$message .= "</body>";
$message .= "</html>";
mail($to, $subject, $message, $headers);
echo "Your email was sent!";
} else {
echo "Invalid Email, please provide an correct email.";
}
The HTML
<form id="contact-form" data-toggle="validator" data-disable="true" role="form">
<div class="form-group">
<label for="name">Navn</label>
<input type="text" name="name" id="contact-name" class="form-control" data-minlength="2" data-error="Please provide a valid name." required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="email">E-mail</label>
<input type="email" name="email" id="contact-email" class="form-control" data-minlength="5" data-error="Please provide a valid e-mail address." required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="message">Your message:</label>
<textarea name="msg" id="contact-email" data-minlength="10" data-error="Your message must be at least 10 characters long." class="form-control" required></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<button id="submit" value="send" class="btn btn-primary">Send</button>
<div id="success"></div>
</div>
</form>
The Javascript
$(document).ready(function(){
$('#success').css('display', 'none');
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
url: "php/form.php",
data: $("#contact-form").serialize(),
type: 'POST',
statusCode: {
500: function(data) {
$('#success').css('display', 'none');
$('#success').css('color', '#A94442');
$('#success').html('Your message was not sent.');
$('#success').fadeIn(200);
},
404: function(data) {
$('#success').css('display', 'none');
$('#success').css('color', '#A94442');
$('#success').html('Your message was not sent.');
$('#success').fadeIn(200);
},
200: function(data) {
console.log(data);
$('#success').css('display', 'none');
$('#success').css('color', '#74C274');
$('#success').html('Your message was sent.');
$('#success').fadeIn(200);
}
}
});
});
});
The e-mail is sent and received, but the textarea is not getting sent through, and it seems to sent the "email" and "name" field twice in the message body.
The e-mail output looks like this:
From:
Someone
Email:
someone#someone.com
Besked:
From:
Someone
Email:
someone#someone.com
Help will be very much appreciated. Have been trying to fix this for hours now.
The error is located here :
$message .= "<p><b>Message:</b><br>" . $message . "</p>";
You are using the same variable for the message to be sent and the message received by your PHP.
This code will be working :
// Get field values.
$name = strip_tags($_POST["name"]);
$email = strip_tags($_POST["email"]);
$message_text = $_POST["msg"];
// Check if e-mail address is valid.
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set e-mail and subject.
$to = "mail#mydomain.dk";
$subject = "You have a new message.";
// Set header values.
$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";
// Set request body.
$message = "<html>";
$message .= "<body>";
$message .= "<p><b>From:</b><br>" . $name . "</p>";
$message .= "<p><b>Email:</b><br>" . $email . "</p>";
$message .= "<p><b>Message:</b><br>" . $message_text . "</p>";
$message .= "</body>";
$message .= "</html>";
mail($to, $subject, $message, $headers);
echo "Your email was sent!";
} else {
echo "Invalid Email, please provide an correct email.";
}
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 7 years ago.
As an mildly-intermediate web developer, I have never actually implemented a contact form until now. The problem is that I can't get the email to actually go through.
HTML:
<form action="php/handleFormSubmit.php" id="contact-form" role="form" method="POST">
<div class="ajax-hidden">
<div class="form-group wow fadeInUp">
<label class="sr-only" for="c_name">Name</label>
<input type="text" id="c_name" class="form-control" name="c_name" placeholder="Name">
</div>
<div class="form-group wow fadeInUp" data-wow-delay=".1s">
<label class="sr-only" for="c_email">Email</label>
<input type="email" id="c_email" class="form-control" name="c_email" placeholder="E-mail">
</div>
<div class="form-group wow fadeInUp" data-wow-delay=".2s">
<textarea class="form-control" id="c_message" name="c_message" rows="7" placeholder="Message"></textarea>
</div>
<button type="submit" class="btn btn-lg btn-block wow fadeInUp" data-wow-delay=".3s">Send Message</button>
</div>
<div class="ajax-response"></div>
</form>
PHP:
<?php
if(isset($_POST['submit']))
{
$name = $_POST['c_name'];
$visitor_email = $_POST['c_email'];
$message = $_POST['c_message'];
$email_from = "email#email.com";
$email_subject = "New Form submission";
$email_body = "You have received a new message from the user $name.\n".
"Here is the message:\n $message".
$to = "email#email.com";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
mail($to,$email_subject,$email_body,$headers);
}
if(isset($_POST['c_name'])){
$res['sendstatus'] = 1;
$res['message'] = 'Form Submission Successful';
echo json_encode($res);
}
?>
I know the if(isset($_POST['submit'])) gets rid of the annoying email when refreshing/landing but my submit does not go to my email.
Help? I appreciate it.
Check the first line,
it says if $_POST['submit'] is set then do this{}.
but your html form doesn't have that field.
ADD this field in your form:
<input type="hidden" name="submit">
Code for sending Mails via Ajax
<?php
if($_POST)
{
$to_email = "er.shakun90#gmail.com"; //Recipient email, Replace with own email here
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING);
//$user_email = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL);
//$country_code = filter_var($_POST["country_code"], FILTER_SANITIZE_NUMBER_INT);
$phone_number = filter_var($_POST["user_phone"], FILTER_SANITIZE_NUMBER_INT);
//$subject = filter_var($_POST["subject"], FILTER_SANITIZE_STRING);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
//additional php validation
if(strlen($user_name)<4){ // If length is less than 4 it will output JSON error.
$output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
die($output);
}
if(!filter_var($phone_number, FILTER_SANITIZE_NUMBER_FLOAT)){ //check for valid numbers in phone number field
$output = json_encode(array('type'=>'error', 'text' => 'Enter only digits in phone number'));
die($output);
}
if(strlen($message)<3){ //check emtpy message
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
$user_email = 'contact#sanktik.net';
//email body
$message_body = $message."\r\n\r\n-".$user_name."\r\nPhone Number :". $phone_number ;
$sunject = "New enquiry from wesbite";
//proceed with PHP email.
$headers = 'From: '.$user_name.'' . "\r\n" .
'Reply-To: '.$user_email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$send_mail = mail($to_email, $subject, $message_body);
if(!$send_mail)
{
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_name .' Thank you for your interest.Our Team Member will get in touch with you shortly'));
die($output);
}
}
?>
Change your button code to:
<button type="submit" name="Submit" class="btn btn-lg btn-block wow fadeInUp" data-wow-delay=".3s">Send Message</button>
and your php file first line to:
if(isset($_POST['Submit']))
Don't check if the button exists in the POST array. It makes sense if you click the button or submit the form via Enter press! I think by submitting via Enter press, the submit button doesn't exist!
Solution below is insensitive:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
// sent
Important things:
Check if form is real posted (see above)
Validate your input
Sanatize your input
After that, you can do your actions, e.g. mail or saving to database.