Unable to send email in PHP through Html Form - php

I design and developed one website in which I have one contact form. I wanted to send inquiry email through contact form. But I am getting following error in console. I tried on local system as well as on server.
Access to XMLHttpRequest at 'file:///E:/clients/website/contact.php' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Here is my HTML Code :
<form id="contactform" action="contact.php" name="contactform" method="post" class="form-validation" autocomplete="off">
<div class="row">
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
<div class="single-input">
<input type="text" placeholder="First Name*" name="Fname" id="Fname">
</div> <!-- /.single-input -->
</div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
<div class="single-input">
<input type="text" placeholder="Last Name*" name="Lname" id="Lname">
</div> <!-- /.single-input -->
</div>
<div class="col-lg-4 col-md-4 col-sm-12 col-xs-12">
<div class="single-input">
<input type="email" placeholder="Your Email*" name="email" id="email">
</div> <!-- /.single-input -->
</div>
</div> <!-- /.row -->
<div class="single-input">
<input type="text" placeholder="Subject" name="sub" id="subject">
</div> <!-- /.single-input -->
<textarea placeholder="Write Message" name="message" id="message"></textarea>
<button type="submit" value="SEND" id="submit" class="tran3s p-color-bg">Send Message</button>
</form>
Here is contact.php
<?php
if(!$_POST) exit;
// Email address verification, do not edit.
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(com|coop|cr|cs)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$Fname = $_POST['Fname'];
$Lname = $_POST['Lname'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
if(get_magic_quotes_gpc()) {
$message = stripslashes($message);
}
$address = "sales#abc.com";
$e_subject = 'You\'ve been contacted by ' . $Fname . '.';
$e_body = "You have been contacted by $Fname with regards to $subject, their additional message is as follows." . PHP_EOL . PHP_EOL;
$e_content = "\"$message\"" . PHP_EOL . PHP_EOL;
$e_reply = "You can contact $Fname via email, $email";
$msg = wordwrap( $e_body . $e_content . $e_reply, 70 );
$headers = "From: $email" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-type: text/plain; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: quoted-printable" . PHP_EOL;
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you <strong>$Fname</strong>, your message has been submitted to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}

XMLHttpRequest does not support file scheme.
You could try this:
Solution 1: Use http/https instead of local file.
I would never use the file protocol for server-side files, if you need to test your .php files locally, it's better to use a localhost (like XAMPP) and test your code.
Solution 2 (don't skip the solution 1): Try this if solution 1 didn't work, but please don't use the file protocol (otherwise it won't work anyway).
Try to add the following header to the HTTP response:
Access-Control-Allow-Origin: *
The header above will allow your scripts to read the response regardless of the origin.
Note: Don't use Access-Control-Allow-Origin: * on your production code, otherwise you're exposing your website to security vulnerabilities.

Related

I have created a form, but posts are not coming

I have created a form, but posts are not coming. Form Code
<form method="post" action="contact.php">
<form class="quote">
<div>
<label>Name</label><br>
<input type="text" placeholder="Name">
</div>
<div>
<label>Email</label><br>
<input type="email" placeholder="Emial Address">
</div>
<div>
<label>Message</label><br>
<textarea placeholder="Message"></textarea>
</div>
<button class="button_1" type="submit">Send</button>
</form>
contact.php code
<?php $to = 'demo#spondonit.com'; $firstname = $_POST["fname"]; $email= $_POST["email"]; $text= $_POST["message"]; $headers = 'MIME-Version: 1.0' . "rn"; $headers .= "From: " . $email . "rn"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn"; $message ='<table style="width:100%"> <tr> <td>'.$firstname.' '.$laststname.'</td> </tr> <tr><td>Email: '.$email.'</td></tr> <tr><td>Email: '.$text.'</td></tr> </table>'; if (#mail($to, $email, $message, $headers)) { echo 'The message has been sent.'; }else{ echo 'failed'; } ?>
Maybe the route of the page is wrong, try:
action="/contact.php">
if it's on the same folder
You really need to provide more detail - what does it mean that posts are not coming? Do you see the "failed" message or nothing at all?
But, most importantly: you use identifiers such as $_POST['fname'] but there is nothing in your HTML indicating that a text input value should be sent as "fname". You need to add a name attribute to all of your <input>s, for example:
<input type="text" name="fname" placeholder="Name">
Neither placeholder= or <label> suffice - they only affect how the form is displayed on the webpage and not how it is sent to the server.

Contact form doesn't work with the new jQuery version (3.3.1)

I was mistaken that I was missing anything from my PHP file. The only thing which makes the contact form working is if I use a way older version of the jQuery but that cannot be the case because I need SSL on my site and Google determines the site unsafe which wants to load unsafe scripts if they are older.
Here is the old version of the scripts:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
window.jQuery || document.write('</script>')
<script type="text/javascript" src="js/jquery-migrate-1.2.1.min.js"></script>
And here is what I was trying to use. I downloaded js files and uploaded to the server but I thinks because of the many function changes my PHP file cannot do the work anymore.
Can somebody help me to update my PHP file because I don't really do coding :o. Tried to understand how it works however I got confused.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-3.3.1.min.js"><\/script>')</script>
<script type="text/javascript" src="js/jquery-migrate-3.0.0.min.js"></script>
I use a template from Styleshout called Kreative101 and modified it in many ways but I didn't touch the contact form nor the PHP file (only inserting the error reporting and the email address).
I don't know if it needs any jQuery script in order to work because I did change that and the Modal Popup stopped working. Now it is back to the original (at least the footer with the scripts). The modal works the contact form doesn't.
Any help will be highly appreciated;).
If a reload the page says the action I took will be repeated
The contact form worked before, I tested it.
Here is the HTML code
<section id="contact">
<div class="row section-head">
<div class="col full">
<h2>Contact</h2>
<p class="desc">Get in touch with us</p>
</div>
</div>
<div class="row">
<div class="col g-7">
<!-- form -->
<form name="contactForm" id="contactForm" method="post" action="">
<fieldset>
<div>
<label for="contactName">Name <span class="required">*</span></label>
<input name="contactName" type="text" id="contactName" size="35" value="" />
</div>
<div>
<label for="contactEmail">Email <span class="required">*</span></label>
<input name="contactEmail" type="text" id="contactEmail" size="35" value="" />
</div>
<div>
<label for="contactSubject">Subject</label>
<input name="contactSubject" type="text" id="contactSubject" size="35" value="" />
</div>
<div>
<label for="contactMessage">Message <span class="required">*</span></label>
<textarea name="contactMessage" id="contactMessage" rows="15" cols="50" ></textarea>
</div>
<div>
<button class="submit">Submit</button>
<span id="image-loader">
<img src="images/loader.gif" alt="" />
</span>
</div>
</fieldset>
</form> <!-- Form End -->
<!-- contact-warning -->
<div id="message-warning"></div>
<!-- contact-success -->
<div id="message-success">
<i class="icon-ok"></i>Your message was sent, thank you!<br />
</div>
</div>
And the PHP code (I inserted the error reporting but I don't know if it's correct.)
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");
// Replace this with your own email address
$siteOwnersEmail = 'info#virtualpropertyreview.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
}
?>
In the comment I suggested to redirect after sending the mail - not sure if you understood what I meant but like this.
$mail = mail( $siteOwnersEmail, $subject, $message, $headers );
header('Location: ?mailsent=' . $mail ? 'true' : 'error' );
That should prevent the form being submitted if the page is reloaded accidentally etc
You could use that GET variable to display a message to report on status of the mail send.
if( !empty( $_GET['mailsent'] ) ){
echo $_GET['mailsent']=='true' ? "your message was sent" : "Sorry, there was an error"; /* etc */
}

Add reCAPTCHA V2

it is already 1 week that I am trying to add a reCAPTCHA V2 module on my static website. (I bought the html5 template since I do not have any experience with web-dev).
That's my html part:
<form action="include/sendmail.php" method="post">
<div class="field">
<label class="required" for="sc_contact_form_username">Name</label>
<input type="text" name="username" id="sc_contact_form_username" />
</div>
<div class="field">
<label class="required" for="sc_contact_form_email">Email</label>
<input type="text" name="email" id="sc_contact_form_email" />
</div>
<div class="field message">
<label class="required" for="sc_contact_form_message">Your Message</label>
<textarea name="message" id="sc_contact_form_message"></textarea>
</div>
<div class="g-recaptcha" data-theme="dark" data-sitekey="MYKEY"></div>
<div class="button"> <a class="enter" href="#"><span>Submit</span></a> </div>
</form>
<div class="result sc_infobox"></div>
So far so good...the difficult part for me it's the PHP, how do I modify the current PHP to add the validation and make it more secure?
<?php
global $_REQUEST;
$response = array('error'=>'');
$user_name = substr($_REQUEST['user_name'], 0, 20);
$user_email = substr($_REQUEST['user_email'], 0, 40);
$user_msg = $_REQUEST['user_msg'];
$contact_email = 'your_mail#mail.com';
if (trim($contact_email)!='') {
$subj = 'Message from ShiftCV HTML';
$msg = "Name: $user_name
E-mail: $user_email
Message: $user_msg";
$head = "Content-Type: text/plain; charset=\"utf-8\"\n"
. "X-Mailer: PHP/" . phpversion() . "\n"
. "Reply-To: $user_email\n"
. "To: $contact_email\n"
. "From: $user_email\n";
if (!#mail($contact_email, $subj, $msg, $head)) {
$response['error'] = 'Error send message!';
}
} else
$response['error'] = 'Error send message!';
echo json_encode($response);
die();
?>
I would suggest you have a look at this composser that you can add to your application to make the required calls and validate the reCaptcha reponse: https://github.com/google/recaptcha

Sending and Receiving mail through php contact form [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 8 years ago.
Recently, I have purchased a domain and hosting. I've also created a webpage having contact form in it. I want when the user wrote something in textarea of contact form and clicks submit then that message is sended to my gmail account and so that i can reply also to those messages. I've also used this script to do so but its not working.
This is sendemail.php file
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Thank you for contact us. As early as possible we will contact you '
);
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'raunakhajela#gmail.com';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
This is my contact form code in index.php
<div class="contact" id="contact">
<div class="container-3x">
<div class="block-header"> <!-- Blocks Header -->
<h2 class="title">Contact Us</h2>
</div>
<div class="block-content"> <!-- Blocks Content -->
<form action="sendemailphp" method="post" class="trigger-form-animate">
<input type="text" value="" id="name" name="name" placeholder="Name *" />
<input type="text" value="" id="email" name="email" placeholder="Email *" />
<input type="text" value="" id="website" name="website" placeholder="Website *" />
<textarea type="text" value="" id="message" name="message" rows="3" placeholder="Your Message *" ></textarea>
<div class="clr"></div>
<button>Submit Message</button>
</form>
</div>
</div>
</div>
I've also tried "http://www.mybloggertricks.com/2012/06/connect-your-website-email-address-to.html" this tutorial but its not working. Unable to find "Send through Gmail (easier to set up)" this option in gmail on adding another accounts windoww.
How can i do that?? Plzz hlp
You don't have a named subject form element which may explain why mail is failing and may very well be sent to Spam instead.
For example: <input type="text" name="subject">. Either add one of replace.
You will however need to make sure that this is filled out using a conditional statement
(see further below for an example).
$subject = #trim(stripslashes($_POST['subject']));
with
$subject = "Form submission";
You could also add this instead to your form:
<input type="hidden" name="subject" value="Form submission">
Either this or what I've outlined just above will work.
Many Email clients will either send mail to Spam or reject it altogether if a "subject" is missing, which is clearly missing from your code.
Checking if subject has been filled example:
if(isset($_POST['subject']) && !empty($_POST['subject'])){
// do someting
}
try this,both will work
<?php
$to = "usermailid#gmail.com";
$subject = "Welcome to";
$message = " Hi $username,<br /><br />
Thank you for signing up with us.<br />
Thanks <br />";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
// More headers
$headers .= 'From: <yourmailid#gmail.com>' . "\r\n";
$mail=mail($to,$subject,$message,$headers);
if($mail)
{
$to = "admin#gmail.com";
$subject = "Following Customer Signed Up";
$message = " $username,Customer is signed up with us,<br /><br />
Customer Details:<br />First Name:$firstname<br/>Last Name:$lastname<br/>Email:$email<br/>
Phone:$phone<br/>Zip Code:$zip<br/>Message:$message_cust<br/><br/><br/>
Thanks <br />";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
// More headers
$headers .= 'From: <yourmailid#gmail.com>' . "\r\n";
$mail=mail($to,$subject,$message,$headers);
}
?>

PHP Mail form showing blank responses

I have a PHP mail form from a Template that sends the email to me, but it appears all the variables are blank.
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Email sent!'
);
$name = #trim(stripslashes($_POST['yourname']));
$email = #trim(stripslashes($_POST['youremail']));
$subject = #trim(stripslashes($_POST['yoursubject']));
$message = #trim(stripslashes($_POST['yourmessage']));
$email_from = $email;
$email_to = 'kylef33#gmail.com';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
?>
And here, the HTML:
<div class="col-sm-6">
<h1>
Contact Form
</h1>
<p>
Fill out the form to enquire directly and we will get back to you as soon as possible.
</p>
<div class="status alert alert-success" style="display: none">
</div>
<form id="main-contact-form" class="contact-form" name="contact-form" method="post" action="sendemail.php" role="form">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<input name="yourname" type="text" class="form-control" required="required" placeholder="Name">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<input name="youremail" type="text" class="form-control" required="required" placeholder="Email address">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<textarea name="yourmessage" id="message" required class="form-control" rows="8" placeholder="Message"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-danger btn-lg">Send Message</button>
<input type="hidden" name="yoursubject" value="Enquiry">
</div>
</div>
</div>
</form>
</div>
But the resulting email is:
Name:
Email:
Subject:
Message:
With none of the responses. Where am I going wrong?
Edit:
If I set the variables manually in the php file the message comes through fine:
$name = 'John';
$email = 'email#email.com;
$subject = 'Enquiry Form';
$message = 'Message here.';
I think the php file isn't getting the variables from the form correctly. How do I fix this?
I don't see the header of the email. try to add this:
$headers = "MIME-Version: 1.0\r\nFrom: $noReplay\r\nReply-To: $noReplay\r\nContent-Type: text/html; charset=utf-8";
where $noReplay is the email address to show to the receiver and the header is sent as a last parameter in mail() function.
Hope this helps!
Keep on coding,
Ares.
Try By use simple code and Set Content-type: text/html in headers it may useful:
$name = $_POST['yourname'];
$email = $_POST['youremail'];
$subject = $_POST['yoursubject'];
$message = $_POST['yourmessage'];
$email_from = $email;
$email_to = 'kylef33#gmail.com';
$body = 'Name: ' . $name . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
//set the headers
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'From: <'.$email_from.'>' . "\r\n";
// Mail it
mail($email_to, $subject, $body, $headers);

Categories