I made a contact form based on this tutorial but I can't get this one to work.
When I hit the submit button, nothing happens (it seems like the page is being refreshed or on my live website it returns to the index.html) and I don't get an email and no response.
I want to get an email containing the content of the form that the user filled out.
This is the ajaxSubmit.php:
<?php
$name = $_POST['name']; // contain name of person
$email = $_POST['email']; // Email address of sender
$web = $_POST['web']; // Your website URL
$body = $_POST['text']; // Your message
$receiver = "xxx#gmail.com" ; // hardcorde your email address here - This is the email address that all your feedbacks will be sent to
if (!empty($name) & !empty($email) && !empty($body)) {
$body = "Name:{$name}\n\nWebsite :{$web}\n\nComments:{$body}";
$send = mail($receiver, 'Contact Form Submission', $body, "From: {$email}");
if ($send) {
echo 'true'; //if everything is ok,always return true , else ajax submission won't work
}
}
?>
xxx#gmail.com is just a placeholder here for my regular email adress, of course.
FIDDLE with html, js and css.
What am I doing wrong?
I reccomend using isset, to check whether the posted variables actually exists, furthermore: I recommend using the ternary operator to check if they are actually set:
$name = isset($_POST['name']) ? $_POST['name'] : false;
$email = isset($_POST['email']) ? $_POST['email'] : false;
$web = isset($_POST['web']) ? $_POST['web'] : false;
$text = isset($_POST['text']) ? $_POST['text'] : false;
$receiver = "xxx#gmail.com"; // You forgot to close a whitespace here.
if(($name && $email && $web && $text) != false)
{
// It's okay to send email now.
// Checkpoint.
}
I recommend using this spam check filtering function:
function spamcheck($field)
{
//address using FILTER_SANITIZE_EMAIL
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
//address using FILTER_VALIDATE_EMAIL
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return true;
}
else
{
return false;
}
}
And I like to use this modified mail function:
// Usage: sendMail($toEmail, $fromEmail, $subject, $message);
// Pre: $toEmail is of type string and is a valid email address,
// indicating the receiver.
// $fromEmail is of type string and is a valid email address,
// indicating the sender.
// $subject is of type string, indicating the email subject.
// $message is of type string, indicating the message to be send
// via the email, from $fromEmail's address to $toEmail's address.
// Post: An email containing $message and the subject $subject from
// $fromEmail's address to $toEmail's address if $fromEmail
// does not indicate a spam email.
function sendMail($toEmail, $fromEmail, $subject, $message)
{
$validFromEmail = spamcheck($fromEmail);
if($validFromEmail)
{
mail($toEmail, $subject, $message, "From: $fromEmail");
}
}
So you can continue from where we loft off. To begin with: You don't really need the curly braces. Also.. you're overwriting the $body variable, it would make more sense to keep the variables seperated. I also recommend storing the subject in a variable.
$subject = 'Contact Form Submission'; // Place where we left of at Checkpoint.
$message = "Name: $name\n\nWebsite :$web\n\nComments:$body"; // Place where we left of at Checkpoint.
sendMail($email, $receiver, $subject, $message); // Place where we left of at Checkpoint.
You also have to make sure that you have access to a SMTP (Simple Mail Transport Protocol), so it might not be enough for you to be working localhost if you don't have a SMTP server to use. IF you have one, and It's not working, then you might have to config the php ini settings:
ini_set('SMTP' , 'smtp.yourwebsite.com');
ini_set('smtp_port' , '25');
ini_set('username' , 'example#example.com');
ini_set('password' , 'pass');
ini_set('sendmail_from' , 'example#example.com');
Note: It would be smart to actually make the modified mail function RETURN the mail function, so that you can check whether it was successful or not.
Related
I am using php mail() for sending email. with this function mail is being sent properly. But after sending mail page is not not loaded properly. Actually I want to land on same page after sending email.
following is the code that I have written
if (isset($_POST['submit'])) { // Check if form was submitted
if (empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['subject']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$subject = strip_tags(htmlspecialchars($_POST['subject']));
$message = strip_tags(htmlspecialchars($_POST['message']));
// Create the email and send the message
$to = 'myemail#gmail.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Subjet : $subject";
$email_body = "You have received a new message from your website contact form.\n\n" . "Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: myemail#gmail.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#gmail.com.
$headers .= "Reply-To: $email_address";
mail($to, $email_subject, $email_body, $headers);
header("Refresh:0");
return true;
// exit();
}
this is contact us page
after sending email this page is not loaded completely only header is loaded
It is probably because the mail sending fails.
You can see the error it is returning by adding the following on top of the PHP file:
ini_set('display_errors', 1);
Also, it is advisable to use PHPMailer, because the mail() function doesn't always work.
I m trying contact form in php.I receive the mails in gmail,yahoo etc but doesnt recieve any mails in hotmail.I tried a lot but doesnt know whats the problem.Why i cant recieve mail in hotmail? Here is the code.
if (empty($error)) {
$to = 'abc#gmail.com, ' . $email;
$subject = " contact form message";
$repEmail = 'abc#gmail.com';
$headers = 'From: Contact Detail <'.$repEmail.'>'.$eol;
$content = "Contact Details: \n
Name:$name \n
Batch: $batch \n
Email: $email \n
mobile: $mobile " ;
$success = "<b>Thank you! Your message has been sent!</b>";
mail($to,$subject,$content,$headers);
}
}
?>
Check the server admin's email for bounce messages. I would guess it has to do with hotmail rejecting it either because it doesn't like your host or because you don't have SPF or DKIM signing set up. Either way, the blame is probably on your server email administrator more than on your code. Email is actually kinda complex to set up nowadays given all the anti-spam stuff you have to do.
You might want to consider using a third party email service. SMTP through a gmail account or Amazon SES so they'll take care of more of these details. This can be set up by the server admin too, or done in PHP with libraries. Is there a SMTP mail transfer library in PHP
this is more likely
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
{
//send email
$email = $_REQUEST['email'] ;
$subject = 'Order' ;
$message =
'Product Name :'. $_REQUEST['proname']."\n". //these all are example details
'Name :'.$_REQUEST['name']."\n".
'Phone :'. $_REQUEST['phone']."\n".
'City :'.$_REQUEST['city']."\n".
'Address :'.$_REQUEST['address']."\n".
'Quantity :'. $_REQUEST['select'];
if ($email == "" || $subject == "" || $message == "" )
{
echo 'Please fill the empty fields';
}
else{
mail("anything#something.com", $subject,
$message, "From:" . $email);
echo 'Thank you ! we will contact you soon';
}
}
I wish to send a copy of the data filled out by the visitor to myself and the other copy to the visitor. Please advice!
My email is myemail#mysite.com while the visitor's email is $email
This code is as seen below:
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "myemail#mysite.com, .$email";
I'm not getting any results after hitting the submit button!
I'll be very grateful!
<?php
// My modifications to mailer script from:
// http://blog.teamtreehouse.com/create-ajax-contact-form
// Added input sanitizing to prevent injection
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$message = trim($_POST["message"]);
// Check that data was sent to the mailer.
if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "myemail#mysite.com, .$email";
// Set the email subject.
$subject = "New contact from $name";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>
You have to put myemail and visitors emails in one array and then run a loop, the same message will be send to all in array.
e.g.
$aEmails = array();
$aEmails[] = 'myemail#something.com';
$aEmails[] = 'visitoremail#something.com';
foreach(aEmails AS aEmail){
mail($aEmail, $subject, $email_content, $email_headers);
}
If you are not getting any result then you must check your html forms' tag it should have method="POST" attribute.
Then in here remove the dot
$recipient = "myemail#mysite.com, .$email";
like this
$recipient = "myemail#mysite.com, $email";
Hello after 3 days of trying to put my form together, I have come across a problem...
Using the form, It can validate when i press submit. which is good, but once i press send, the invalid data still gets sent to my inbox.. so I will end up with two emails.. one with invalid data and then one with the valid data which is typed in after the error messages have been displayed and re-sent. If anyone can look at my code and see what I am missing, or have done wrong i will appreciate it soo much
<?php
if (isset($_POST['submit'])) {
//check email
if(empty($_POST['email_addr']))
$msg_email = "*";
$email_subject = $_POST['email_addr'];
$email_pattern = '/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/';
preg_match($email_pattern, $email_subject, $email_matches);
if(!$email_matches[0])
$msg2_email = "Please enter a valid email address";
}
// validation complete
if(isset($_POST['submit'])){
if($msg_name=="" && $msg2_name=="" && $msg_email=="" && $msg2_email=="")
$msg_success = "Thankyou for your enquiry";
//send mail
$EmailFrom = "someone#somewhere.com";
$EmailTo = "someone#somewhere.com";
$Subject = "Online contact form";
$email_addr = Trim(stripslashes($_POST['email_addr']));
}
// prepare email body text
$Body = "";
$Body .= "email_addr: ";
$Body .= $email_addr;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: $EmailFrom");
?>
I would not use your regular expression to validate email addresses. I'd use filter_var instead.
if( !filter_var($_POST['email_addr'], FILTER_VALIDATE_EMAIL) ) {
$msg2_email = "Please enter a valid email address";
}
filter_var returns false if the filter fails, otherwise it returns the filtered email address.
On top of that, you can set a default value if your filter fails. For example, suppose that the email address field is not necessary, so instead writing yet another line of code to check for null-ness in your variables like:
$isEmailNull = ( $_POST['email_addr'] === NULL) ? NULL : $_POST['email_addr'];
with filter_var you can write it like:
$emailAddress = filter_var( $_POST['email_addr'], FILTER_VALIDATE_EMAIL,
array('options' => array(
'default' => null
)
));
If your filter fails, then $emailAddress is not false, but null. Which makes more sense for non-boolean variables.
You can read more about filter_var here
you can validate/sanitize IP addresses, URLs, Email addresses, ASCII characters, numbers, etc... without using regular expressions that may or may not work.
I have a single page portfolio website that I'm building and I have a contact form that I need to process using php send script. I'm a novice when it comes to PHP so I'm having trouble getting this to work. I've done some searching but I can't find what I'm looking for.
Here's what I have done, I copied this from a PHP contact page that I had built but the PHP and form are on the same page and I need an external send.php to process my form.
<?php
$error = ''; // error message
$name = ''; // sender's name
$email = ''; // sender's email address
$company = ''; // company name
$subject = ''; // subject
$comment = ''; // the message itself
if(isset($_POST['send']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$company = $_POST['company'];
$subject = $_POST['subject'];
$comment = $_POST['comment'];
if($error == '')
{
if(get_magic_quotes_gpc())
{
$message = stripslashes($message);
}
// the email will be sent here
// make sure to change this to be your e-mail
$to = "example#email.com";
// the email subject
// '[Contact Form] :' will appear automatically in the subject.
// You can change it as you want
$subject = '[Contact Form] : ' . $subject;
// the mail message ( add any additional information if you want )
$msg = "From : $name \r\ne-Mail : $email \r\nCompany : $company \r\nSubject : $subject \r\n\n" . "Message : \r\n$message";
mail($to, $subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n");
}
}
if(!isset($_POST['send']) || $error != '')
{
header("location: http://www.#.com/#contact");
}
?>
So for my form I want to have:
<form method="post" action="send.php" class="form">
I plan on using HTML5 and jQuery to validate the form, so I really only need the script to capture the info and send the email to a single address. After it sends I want the script to redirect back to the Contact page.
Edit:
I found a solution after spending a while on google.
http://www.website.com/#contact");
?>
For one thing, you haven't initialized the value for $message
$message = stripslashes($message);
You probably meant to use $comment instead of $message
Not sure what problem you're facing. Simply copy the PHP you have into a file called send.php and my first glance says it'll work if you change $message back to $comment and add error checking. If you still have issues, post back with more details.