I have a contact form on my website, which actually works :D
The problem is, that the email ends up in the spam folder. I have tried to do stuff with the header section, but nothing seems to work.
Can anyone help me with this?
thanks
<?php
ini_set("display_errors", "0");
$post_data = filter_input_array( INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS );
$name = $post_data["name"];
$email = $post_data["email"];
$phone = $post_data["phone"];
$website = $post_data["website"];
$message = $post_data["message"];
# select data that needs validation
$validate = array(
'required' => array($name,$email,$message),
'validEmail' => array($email),
'validNumber' => array($phone),
'validAlpha' => array($name)
);
$formcontent = "Name: $name \nE-Mail: $email \nPhone: $phone \nWebsite: $website \nMessage: $message \n";
$formcontent = wordwrap($formcontent, 70, "\n", true);
$recipient = "thomas.teilmann#gmail.com";
$subject = "Contact Messenbrink.eu";
/*$mailheader = "From: $email \r\n";**/
$mailheader .= "Reply-To: $name <$email>\r\n";
$mailheader .= "Return-Path: $name <$email>\r\n";
$mailheader .= "Content-Type: text/plain\r\n";
$mailheader .= "Organization: Sender Organization\r\n";
$mailheader .= "MIME-Version: 1.0\r\n";
$mailheader .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$mailheader .= "X-Priority: 3\r\n";
$mailheader .= "X-Mailer: PHP". phpversion() ."\r\n";
$mailheader .= "From: $name <$email>\r\n";
function sendMail() {
global $formcontent, $recipient, $subject, $mailheader;
mail($recipient, $subject, $formcontent, $mailheader);
}
# error messages
$errorsMsgs = array(
'required' => 'Please fill out all required fields.',
'validEmail' => 'is an invalid email address.',
'validNumber' => 'is an invalid number.',
'validAlpha' => 'contains invalid characters. This field only accepts letters and spaces.'
);
$errorMarkup = "<h1>We found a few errors :-(</h1><h2>Please fix these errors and try again</h2><ol>";
$errorMarkupEnd = "</ol>";
$successMarkup = "<h1>Success!</h1><h2>Your form was sent successfully.</h2>";
$backMarkup = "Back to form";
# begin state
$valid = true;
# loop through fields of error types
foreach ($validate as $type => $fields) {
# loop through values of fields to be tested
foreach ($fields as $value) {
# throw error if value is required and not entered
if ($type === 'required' && strlen($value) === 0) {
$errorMarkup .= "<li>$errorsMsgs[$type]</li>";
$valid = false;
break;
}
else if (
$type === 'validEmail' && !filter_var($value, FILTER_VALIDATE_EMAIL) ||
$type === 'validNumber' && !preg_match('/^[0-9 ]+$/', $value) ||
$type === 'validAlpha' && !preg_match('/^[a-zA-Z ]+$/', $value)
) {
if (strlen($value) === 0) {break;} # skip check if value is not entered
$errorMarkup .= "<li>\"$value\" $errorsMsgs[$type]</li>";
$valid = false;
continue;
}
}
}
if ($valid) {
sendMail();
$body = $successMarkup . $backMarkup;
$title = "Form sent";
} else {
$body = $errorMarkup . $errorMarkupEnd . $backMarkup;
$title = "Form errors";
}
# write html ouput
echo "<!DOCTYPE html><head><title>$title</title><style type=\"text/css\">body{margin:100px;font:16px/1.5 sans-serif;color:#111}h1{font-size:32px;margin:0;font-weight:bold}h2{font-size:18px;margin:0 0 20px 0}ol,li{list-style-position:inside;padding-left:0;margin-left:0}</style></head><body>$body</body></html>";
?>
It has nothing to do with the PHP code but make sure that the email are being sent from a domain that is hosted on the server. That means it would be a bad idea to use your gmail address for sending though PHP. Every email that leaves the server needs to be signed and needs to have SPF records
This is usually because in the DNS a correct SPF record has not been setup. This can be easily done depending on the software you use. If you use cPanel then this is pretty much a two step process.
Some links:
http://www.emailquestions.com/help-desk/2418-why-do-my-own-emails-go-into-spam.html
http://www.google.co.uk/search?sourceid=chrome&ie=UTF-8&q=spf+records
http://www.techtalkpoint.com/articles/setting-up-spf-records-in-cpanel-whm-and-namecheap/
Ensure the message source is valid. Other than that, there isn't a lot you can do in PHP. The rest is down to your message contents, your mail server and the recipient server's spam filter.
Try to ensure that the data in your headers matches what would normally appear in a normal message. For instance, it is best that your From and Return-Path domain name match the server you are sending from.
I notice you just use \n as a line delimiter in the body. It should be \r\n irrespective of the OS you are using.
Ideally, study RFC 2822. If you don't have time to do that, at the very least, compare your headers with other emails that you believe to be valid. Where possible, match the order of headers, including placing the same number of blank lines in the appropriate places.
Spam isn't filtered by some setting, it's filtered by your word choice and how the message looks and also how well known the sender email address is. If you want to avoid the spam list, you have to word it in a way that does not sound spammy.
My one suggestion would be to have the email's From address be the email address of the actual mail account you're using to send these rather than the customer's email account. Your email provider may think they're spoofing if the email comes from their email address but not from a server on that domain.
You could instea put the customer's email address in the body of the email so you know who it's from.
It's probably the smtp being used that is not valid.
If the contact form is just used to send emails to one mailfolder, I would just set up a rule there to not mark it as spam. Either that or actually validate your smtp.
I was having a similar problem with Gmail, I just selected the email and set to "Not Spam" now all emails sent by my server, when someone uses the contact form on my site end up on Inbox folder. Hope this helps.
Related
I am trying to send email from a web page hosted on a shared platform over at fasthosts. I cannot for the life of me get this to work, I had a much more extensive script which checked the validity of email etc, but now I've been reduced to using the basic example from fasthosts and it is still not working.
Please could someone take a look and let me now where I am going wrong...
<?php
// You only need to modify the following two lines of code to customise your form to mail script.
$email_to = "contact#mywebsite.co.uk"; // Specify the email address you want to send the mail to.
$email_subject = "Feedback from website"; // Set the subject of your email.
// This is the important ini_set command which sets the sendmail_from address, without this the email won't send.
ini_set("contact#mywebsite", $email_from);
// Get the details the user entered into the form
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
// Validate the email address entered by the user
if(!filter_var($email_from, FILTER_VALIDATE_EMAIL)) {
// Invalid email address
die("The email address entered is invalid.");
}
// The code below creates the email headers, so the email appears to be from the email address filled out in the previous form.
// NOTE: The \r\n is the code to use a new line.
$headers = "From: " . $email_from . "\r\n";
$headers .= "Reply-To: " . $email_from . "\r\n"; // (You can change the reply email address here if you want to.)
// Now we can construct the email body which will contain the name and message entered by the user
$message = "Name: ". $name . "\r\nEmail: " . $email . "\r\nMessage: " . $message ;
// Now we can send the mail we've constructed using the mail() function.
// NOTE: You must use the "-f" parameter on Fasthosts' system, without this the email won't send.
$sent = mail($email_to, $email_subject, $message, $headers, "-f" . $email_from);
// If the mail() function above successfully sent the mail, $sent will be true.
if($sent) {
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$name .' Thank you for contacting us.'));
die($output);
} else {
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}
?>
I have written a php mail function to allow a user on my website to fill in a form and send the form to my email. as the question says the email is working once the user send the form however it only appear in my junk email folder instead, i am not a php developer but after doing some research i have noticed a lot people mentione about PHPMailer which i never heard of or used before.
i would much appreciate with a bit oh help.
$to="myemail.com";
//Errors
$nameError="";
$emailError="";
$errMsg="";
$errors="";//counting errors
$name="";
$email="";
$message="";
if(isset($_POST['send'])){
if(empty($_POST['yourname'])){ //name field empty
$nameError="Please enter your name";
$errors++; // increament errors
}else{
$name= UserInput($_POST['yourname']);
if(!preg_match("/^[a-zA-Z ]*$/", $name)){
$nameError="Only letters and white space accepted";
$errors++;
}
}
if(empty($_POST['email'])){
$emailError="Enter email";
$errors++;
}else{
$email = UserInput($_POST['email']);
if(!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)){
$emailError="Invalid Email";
$errors++;
}
}
if(empty($_POST['msg'])){
$errMsg="Enter message";
$errors++;
}else{
$message=UserInput($_POST['msg']);
}
if($errors <=0){//No errors lets setup our email and send it
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: <' . $email . '>' . "\r\n";
$text = "<p>New Message from $name </p>";
$text .= "<p>Name : $name</p>";
$text .= "<p>Email : $email</p>";
$text .= "<p>Message : $message</p>";
mail($to, "Website Contact", $text, $headers);
$success="Thank your message was submitted";
$_POST= array(); //clearing inputs fields after success
}
}
//Filter user input
function UserInput($data){
$data = trim($data);
$data = stripcslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Your using the email from their posted variable in your header. When your email server receives this it's going to look like it is spoofed because it is. Your site isn't going to be one of the mail servers setup for that domain.
When setting up MX and DNS records for email you use SPF or key signing to prove who sent the message and that it came from a trusted mail server for that domain. You may want to change the from to be an email and domain you control. You are getting their email in the body anyway.
Worst case if you don't have control over SPF records you could at least mark the from email, assuming it is something you control, as always trusted so it wouldn't go into your junk mail.
$headers .= 'From: <' . $to . '>' . "\r\n";
I have been looking at this for hours now, and I can't figure out why this won't work. I'm trying to send an email using the mail function. For some reason this page works when hosted by iPage, but not by Godaddy. What is the reason for this?
The PHP:
<?php
// Run code if button pressed
if (isset($_POST['submit'])) {
// Makes sure all fields are filled
if (!$_POST['name'] | !$_POST['email'] | !$_POST['message'] ) {
?><script>alert('You forgot to fill in a field');window.location = "http://example.com/contact.php";</script>
<?php
exit;
}
// From the form
$name = trim(strip_tags($_POST['name']));
$email = trim(strip_tags($_POST['email']));
$message = htmlentities($_POST['message']);
$to = 'email#gmail.com';
$subject = "Contact form submitted!";
$body = <<<HTML
$message
HTML;
$headers = "From: $email\r\n";
$headers .= "Content-type: text/html\r\n";
// send the email
mail($to, $subject, $body, $headers);
?><script>alert('Thanks! I will try to get back to you as soon as possible.');window.location = "http://example.com/contact.php";</script><?php
}
?>
You need to look at your if condition you need || to do a OR
<?php
// Run code if button pressed
if (isset($_POST['submit'])) {
// Makes sure all fields are filled
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['message']) ) {
?>
<script>alert('You forgot to fill in a field');
window.location = "http://example.com/contact.php";
</script>
<?php
exit;
}
You are setting From email id $email from user Input, that means its not configured at your server, add a Reply-To header to $email
$headers = "From: youremail#yourdomain.com \r\n";
$headers .= 'Reply-To: '.$email. "\r\n" .
$headers .= "Content-type: text/html\r\n";
Final note, I would suggest you to use Swift Mailer or PHP Mailer to make it simple
For people having trouble sending email on GoDaddy's servers, here's whats going on:
To prevent spam, GoDaddy's servers refuse to send your mail if your using a certain domain (see below for the list). So to solve the specific problem here, I had to change the domain I was using, so $to = 'email#gmail'; is now $to = 'email#something-else.com';
Here is GoDaddy's explanation and the list of blacklisted domains:
Forms are popular on websites; they let customers share their information with you, whether it’s for a newsletter or to register an account. Often times, these forms email a confirmation of the visitor’s submission to to you or the visitor submitting the information. Did you know that all email, even if it’s sent from a hosting account, must have information entered in the From value, though?
You can make that From value a particular email address, too. This lets you create a professional-looking email for your customers or something that’s easy to categorize for yourself.
However, we have to be careful with what users can specify as their From value to combat spamming attempts. Here’s a list of email address domain names we don’t let our customers use as the From value of their forms:
gmail.com
aol.com
aim.com
yahoo.com
hotmail.com
live.com
msn.com
If your email form uses one of these domain names for its From email address, our server will not send the email.
I'm creating a simple mail form with checkboxes, a couple of input tabs, and a text input section. It uses PHP to retrieve the information then email it to a specific email. Right now I have it emailing to my own yahoo email just for testing. When I test the site on my hosting account jacobbuller.com/testsites/peacock/contact.php the form works perfectly and forwards the email from my generic "theski" server email. But when I upload the site to the actually live hosting account for peacockautoservice.com the contact form works - it executes and sends a ?msg=1 variable in the url - but I never receive the email in my Yahoo account...
Here's the PHP I am using to send the email.
<?php ob_start();
<?php
$required_field = array('name', 'email', 'message');
foreach($required_field as $fieldname) {
if (!isset($_POST[$fieldname])) {
$errors[] = $fieldname;
}}
if (empty($errors)) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$contact = $_POST['contact'];
$phone = $_POST['phone'];
$services = IsChecked('checkboxes', 'factory');
$services .= IsChecked('checkboxes', 'timing belt');
$services .= IsChecked('checkboxes', 'brakes');
$services .= IsChecked('checkboxes', 'computerized');
$services .= IsChecked('checkboxes', 'steering and suspension');
$services .= IsChecked('checkboxes', 'heating and air');
$services .= IsChecked('checkboxes', 'electrical');
$services .= IsChecked('checkboxes', 'other');
$body = "Customer:" . $name;
$body.= "Phone Number:" . $phone;
$body.= "Contact:" . $contact;
$body.= "Services:" . $services;
$body.= "Message:" . $message;
$to = "jcbbuller#yahoo.com";
$subject = "Peacock Auto Services Inquirey";
$from = $email;
$mailed = mail($to, $subject, $body, $from) or die("Error!");
}
if($mailed) {
redirect_to("../contact.php?msg=1");
}
?>
<?php
// IsChecked FUNCTION - Detemines what checkbox are/aren't checked on form.
function IsChecked($postname, $value){
if(!empty($_POST[$postname])) {
foreach($_POST[$postname] as $job) {
if ($job == $value) {
$project = " ". $value . " ";
return $project;
}
}
}
} //END IsChecked FUNCTION
function redirect_to( $location = NULL ) {
if ($location != NULL) {
header("Location: {$location}");
exit;
}
}
?>
<?php ob_end_flush(); ?>
Please let me know if you see something wrong with the PHP above or if you know why their GoDaddy hosting account is not executing the email. I tried using their customer service network but they said that they can't help me with my code...
Your issue is mainly at server end. Mail function is working because of your check on it, if it had failed, it would have given you notification. So, mails are going definitely. If mail server is working properly at your production server, then check for SPAM folder at yahoo mail server. I would suggest you to ask your hosting provider to enable SPF and DKIM records because most of email providers requires sender authentication (if it is not a spam) and these records are helpful in it.
I can also see that your not using any headers, so I would suggest you to use extended headers to avoid providers identifying you as a spammer. I use below mentioned headers and my emails never go in spam on anyprovider, but again it depends on IP reputation of the server as well.
$headers .= "Reply-To: Awaraleo <email#domain.org>\r\n";
$headers .= "Return-Path: Awaraleo <email#domain.org>\r\n";
$headers .= "From: Awaraleo <email#domain.org>\r\n";
$headers .= "Organization: Awaraleo\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "X-Priority: 3\r\n";
$headers .= "X-Mailer: PHP". phpversion() ."\r\n";
and then use it like
mail($to,$subject,$message,$headers);
Here email#domain.org should be a valid email address created on the domain where this form is implemented.
Another authentic way is to use SMTP Authentication in coding.
I'm sending e-mails through a form I coded and for some reason, for some cases the e-mail address becomes junk, and for other times it works fine.
//on form page
$message = str_replace("#e",$emtemail,$message);
$message is stored in SQL (defined on another page), same for $emtemail. $message is just the body of the e-mail being sent, and I'm replacing all instances of #e with the e-mail people send payments to. It sends one e-mail to the customer, and one e-mail to me.
//customer e-mail
//the display address might appear as payment52.62gmail.com instead of payment#gmail.com
//my e-mail
//all e-mail addresses formatted properly without error, # appears as #
Why do e-mail addresses parse strangely? Something to do with encoding?
This is all of the code relevant to sending e-mails I have. I can't pinpoint the problem.
//any variables used in the below but not declared are previously initialized
$em = $userc["email"];
$subject = $emailone["subject"];
$subject = str_replace("#o",$ordernum,$subject);
$subject = str_replace("#u",htmlspecialchars($rn),$subject);
$subject = str_replace("#g",$gt,$subject);
$subject = str_replace("#sl","www.SZVapor.com",$subject);
$subject = str_replace("#ss","SZVapor.com",$subject);
$subject = str_replace("#st","SZVapor",$subject);
$message = nl2br($emailone["message"]);
$message = str_replace("#o",$ordernum,$message);
$message = str_replace("#u",htmlspecialchars($rn),$message);
$message = str_replace("#t",$table,$message);
$message = str_replace("#e",$emtemail,$message);
$message = str_replace("#g",$gt,$message);
$message = str_replace("#a",$addrsubmit,$message);
$message = str_replace("#sl","www.SZVapor.com",$message);
$message = str_replace("#ss","SZVapor.com",$message);
$message = str_replace("#st","SZVapor",$message);
$message = str_replace("#c",$em,$message);
$headers = "MIME-Version: 1.0"."\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1"."\r\n";
$headers .= "From: no-reply#SZVapor.com";
mail($em, $subject, $message, $headers);
Some examples of e-mail addresses given:
payment62.44gmail.com
payment54.45gmail.com
payment22.59gmail.com
payment25.49gmail.com
http://php.net/manual/en/function.mail.php
The first parameter entry for mail is the email address.
The code above does not do anything with $em
And by the way, I think that the last header line should look like this:
$headers .= "From: no-reply#SZVapor.com" . "\r\n";
I solved the issue, and it was an error on my part. I was replacing all instances of certain character combinations with variables.
#g = replaced with grand total
#e = replaced with payment e-mail
#o = replaced with order number
etc
The order I did them in was such that I replaced #e with the e-mail payment#gmail.com, and then replaced all #g with the grand total, so payment*#g*mail.com became "payment".$grandtotal."mail.com".