This question already has answers here:
How do you make sure email you send programmatically is not automatically marked as spam?
(24 answers)
Closed 2 years ago.
I know this problem has been addressed a few times on here. I tried following the directions for setting proper headers, I still run into problems with my emails going into the spam filter in Gmail.
If anyone can please take a look at what I've tried, I'd really appreciate it. The code below is without the headers added as explained here: http://www.velvetblues.com/web-development-blog/avoid-spam-filters-with-php-mail-emails/
Thanks in advance.
define("WEBMASTER_EMAIL", 'myName#mydomain.com');
if($post)
{
$name = stripslashes($_POST['name']);
$email = trim($_POST['email']);
$subject = trim($_POST['subject']);
$message = stripslashes($_POST['message']);
$error = '';
// Check name
if(!$name)
$error .= 'Name required! ';
// Check email
if(!$email)
$error .= 'E-mail required! ';
if($email && !ValidateEmail($email))
$error .= 'E-mail address is not valid! ';
// Check message
if(!$message)
$error .= "Please enter your message!";
if(!$error)
{
$mail = mail(WEBMASTER_EMAIL, $subject, $message,
"From: ".$name." <".$email.">\r\n"
."Reply-To: ".$email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
echo 'OK';
}
else
echo '<div class="errormsg">'.$error.'</div>';
}
Use this code :
$to = Email;
$subject = subject ;
$body = "<div> hi hi .. </div>";
$headers = 'From: YourLogoName info#domain.com' . "\r\n" ;
$headers .='Reply-To: '. $to . "\r\n" ;
$headers .='X-Mailer: PHP/' . phpversion();
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
if(mail($to, $subject, $body,$headers)) {
echo('<br>'."Email Sent ;D ".'</br>');
}
else
{
echo("<p>Email Message delivery failed...</p>");
}
I think this is your issue:
"From: ".$name." <".$email.">\r\n"
since you are not gmail, hotmail or your users email provider, you cannot have "From: otherdomain.com" and then deliver the mail via "mail.yourdomain.com" - this will most likely move your mail to the spam folder.
Try
"From: YourWebsiteName <noreply#yourwebsite.com>\r\n"
."Reply-To: ".$name." <".$email.">\r\n"
instead.
ALso: your code is very unsave and a prime spam target - google "email header injection php"!
Google tends to discipline not only the websites but also service providers who used to have many users spamming across the network.
If you are signed up to one of these service providers that google recognizes as spammers this might be the reason why your php mail() messages drops in to spam box in gmail. Try to chat about this issue with your server provider.
In that case you will get a warning from google in your "spam" message:
"Why is this message in Spam? We've found that lots of messages from
home.pl are spam. Learn more"
I know this question has been asked ages ago, but I thought I'd drop a 2020 answer here so that it can potentially help new visitors.
Please note:
This answer serves as a generic answer and will require you to edit some of the details according to form inputs that you are using.
You also need to update the email address in the headers etc. to the one connected to your domain.
This solution assumes you're using Google Recaptcha. If not, then just delete the part about "Google recapthca".
This script has added security and validation that shouldn't be removed.
If you're going to use Sweet Alert then you should install it into your website/app, either via CDN or NPM.
Some Javascript to create custom Sweet Alert alerts that trigger on mail send:
// Custom SweetAlert alert that gets triggered on email send
function enquirySent() {
swal({
title: "Email sent!",
text: "Thank you for your email. We'll be in contact ASAP.",
icon: "success",
button: "Okay",
});
}
function enquiryNotSent() {
swal({
title: "Oops!",
text: "Your email was NOT sent due to an error.",
icon: "error",
button: "Okay",
});
};
The PHP script to send the mail:
<?php
if (isset($_POST['submit'])) {
// For the Google recaptcha
$curlx = curl_init();
curl_setopt($curlx, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($curlx, CURLOPT_HEADER, 0);
curl_setopt($curlx, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curlx, CURLOPT_POST, 1);
$post_data = [
'secret' => 'YOUR CAPTCHA SECRET KEY',
'response' => $_POST['g-recaptcha-response']
];
curl_setopt($curlx, CURLOPT_POSTFIELDS, $post_data);
$resp = json_decode(curl_exec($curlx));
curl_close($curlx);
// Google recaptcha end
// Form details (sanitized)
$name = htmlspecialchars($_POST['name']);
$surname = htmlspecialchars($_POST['surname']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
// Mail headers and details
$email_from = 'youremail#yourdomain.com';
$email_body = "You have received a new message from the user $name $surname.\nHere is the message:\n\n".$message;
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: ".$email."\r\n";
$headers .= "Return-Path: ".$email."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "X-Priority: 3\r\n";
$headers .= "X-Mailer: PHP". phpversion() ."\r\n" ;
$error = false;
// Some more input validation/sanitizing
if (!preg_match("/^[a-zA-Z ]*$/",$first_name) && $first_name!="") {
$error = true;
}
if (!preg_match("/^[a-zA-Z ]*$/",$last_name) && $last_name!="") {
$error = true;
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL) && $email!="") {
$error = true;
}
function IsInjected($str) {
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if (preg_match($inject,$str)) {
return true;
} else {
return false;
}
}
if (IsInjected($visitor_email)) {
echo "Bad email value!";
exit;
}
// Sending the email
if ($error == false) {
$to = "youremail#yourdomain.com";
$subject = "Enquiry from website";
mail($to, $subject, $email_body, $headers);
// Calling the email sent / not sent alerts
echo '<script type="text/javascript">',
'enquirySent()',
'</script>';
} else {
echo '<script type="text/javascript">',
'enquiryNotSent()',
'</script>';
}
}
?>
Related
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
So I have a simple php file that gets data from a form and is supposed to email me. It works on my own system when I was testing it on localhost. But, when I deployed it on ubuntu using apache2, it didn't work. the file may not be pretty, my first attempt to email with php, but i've included the php file below. I know it gets to the mail() method and fails, it activates the (!$mail) conditional, but I can't ever print $mail or any errors so I have no clue what is wrong. any ideas? The cluster of echoes was my attempt to print some kind of error message with no luck. Also, I actually send it to my email address, I just changed it for this example
<?php
if(!isset($_POST['submit'])){
echo "error; you need to submit the form!";
}
$visitor_name = $_POST['name'];
$visitor_message = $_POST['message'];
//incase the email isn't provided
if(empty($_POST['email'])){
$visitor_email = 'n/a';
} else {
$visitor_email = $_POST['email'];
}
//incase the phone isn't provided
if(empty($_POST['phone'])){
$visitor_phone = 'n/a';
} else {
$visitor_email = $_POST['email'];
}
//incase the phone isn't provided
if(empty($_POST['phone'])){
$visitor_phone = 'n/a';
} else {
$visitor_phone = $_POST['phone'];
}
if(empty($visitor_name) || empty($visitor_message))
{
echo "Name and message are mandatory!";
exit;
}
//a function created below for security purposes
if(IsInjected($visitor_email))
{
echo "Bad email value!";
exit;
}
// **************************** CODE FOR EMAIL BODY BELOW *****************************************
$email_body = '<html><body>';
$email_body .= "<h2> You've recieved a new message from: $visitor_name, they need a building </h2>";
$email_body .= '<h4> Here is the message: </h4>';
$email_body .= "<p> $visitor_message </p>";
$email_body .= "<h4> Their contact info is below</h4>";
$email_body .= "<ul> <li> email: $visitor_email </li>";
$email_body .= "<li> phone: $visitor_phone </li></ul>";
$email_body .= '</body></html>';
// **************************** END OF CODE FOR EMAIL BODY ****************************************
$to = 'j#example.com';
$subject = "Building Form Submission: $visitor_name Needs a building\r\n";
$headers = "From: building-form#ArchitectureAdvertisingWebsite.com \r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if($visitor_email != 'n/a'){
$headers .= "Reply-To: $visitor_email \r\n";
}
$mail = mail($to, $subject, $email_body, $headers);
print_r ($mail);
echo "end test";
if (!$mail){
echo "Message not sent, there was an error. Please contact Jerrod at .....";
$errorMessage = error_get_last();
echo "There was an error: $errorMessage";
echo "Below the error is printed : ";
print_r(error_get_last());
} else {
echo "Message sent";
header('Location: end.html');
}
// Function to validate against any email injection attempts
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>
Emails sent directly by a PHP script in this way typically get marked as junk or spam by the major email providers. If you start sending them in any quantity, your email address (and possibly domain) will end up on Spamhaus and other blacklists.
If you need to send individualized emails like your example above, consider using a service like SendGrid or Amazon Simple Email Service.
my form is working as intended but for some reason the email will only send to one of my email accounts and not the other I am putting the right email in the email field so that isn't the issue however I can't seem to see where I am going wrong I assume it's because I'm using $email to grab the email address to where the 2nd email is suppose to go...here is my php where am I going wrong?
<?php
$from = 'Pixel Wars - Press Inquiry';
$to = "my-email#gmail.com, $email";
$subject = 'Press Inquiry from Pixelwars.com';
function errorHandler ($message) {
die(json_encode(array(
'type' => 'error',
'response' => $message
)));
}
function successHandler ($message) {
die(json_encode(array(
'type' => 'success',
'response' => $message
)));
}
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$body = "Name: $name\r\n Email: $email\r\n\r\n Message:\r\n $message";
$pattern = '/[\r\n]|Content-Type:|Bcc:|Cc:/i';
if (preg_match($pattern, $name) || preg_match($pattern, $email) || preg_match($pattern, $message)) {
errorHandler('Header injection detected.');
}
// Check if name has been entered
if (!$_POST['name']) {
errorHandler('Please enter your name.');
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
errorHandler('Please enter a valid email address.');
}
// Check if message has been entered
if (!$_POST['message']) {
errorHandler('Please enter your message.');
}
// prepare headers
$headers = 'MIME-Version: 1.1' . PHP_EOL;
$headers .= 'Content-type: text/plain; charset=utf-8' . PHP_EOL;
$headers .= "From: $name <$email>" . PHP_EOL;
$headers .= "Return-Path: $to" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "X-Mailer: PHP/". phpversion() . PHP_EOL;
// send the email
$result = #mail($to, $subject, $body . "\r\n\n" .'------------------ '. "\r\n\n" .'Hello '.$name.' we will contact you as soon as possible about your query.' ."\n". 'Dont forget to keep visiting www.pixelwars.com for more updates and awesome content.' ."\n". 'We will email you back on the provided email below, thank you and have a nice day.' . "\r\n\n" .'-- '.$email, $headers);
if ($result) {
successHandler('Thank You! we will be in touch');
} else {
errorHandler('Sorry there was an error sending your message.');
}
} else {
errorHandler('Allowed only XMLHttpRequest.');
}
?>
Thank you in advance if anyone can crack it
You don't have $email assigned when you are defining $to so your second address is not set.
Demo: https://3v4l.org/QIIJu
Solution, move the $to assignment to later in the script. Also use error reporting, this would have thrown an undefined variable notice.
e.g.
<?php
$from = 'Pixel Wars - Press Inquiry';
$subject = 'Press Inquiry from Pixelwars.com';
....
$to = "my-email#gmail.com, $email";
$result = #mail($to, $subject, $body ....
because at this point the $email is defined. Also don't use error suppression, that is just hiding useful information. If you don't want it displayed hide the error displaying but still log them.
You need to add the multiple email address in $to
$to = "address#one.com, address#two.com, address#three.com"
Needs to be a comma delimited list of email adrresses.
mail($email_to, $email_subject, $thankyou);
Thanks
Please advise if the form validation script below is secure enough to avoid most types (all types?) of contact form exploits? I ahve found this script online, added some extra php finctions in hope to make it safer, but not complitely sure if it is good for the purpose.
if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
// 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 = "email_here";
// 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 = "MIME-Version: 1.0\r\n";
$email_headers .= "Content-type: text/html; charset=utf-8\r\n";
$email_headers .= "From: $name <$email>\r\n";
$email_headers .= "Reply-To: $email\r\n";
$email_headers .= "Return-Path: $email\r\n";
$email_headers .= "Organization: Bilingual Counselling\r\n";
// 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.";
}
}
It's not safe. For example you don't do anything with $message - you should probably use strip_tags() function here. Now you put anything that this variable holds straight into e-mail content.
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.
Ive got a contact form that isnt sending but is outputting that the message is sent? Can anybody see a problem?
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$to = "myemail#email.co.uk";
//begin of HTML message
$message = "
From : $name,
Email: $email,
Subject: $subject,
Message: $message ";
//end of message
// To send the HTML mail we need to set the Content-type header.
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: Website Enquiry";
if (isset($_POST['name'])) {
// now lets send the email.
mail($to, $subject, $message, $headers);
header('Location: ' . $_SERVER['HTTP_REFERER'] . '?e=Thankyou, we will be in touch shortly.');
} else {
header('Location: ' . $_SERVER['HTTP_REFERER'] . '?e=There was an error sending your message, Please try again.');
}
?>
The "From" header should have a syntactically correct email address. You also need to check the return value of the "mail" function.
$header .= "From: Website Enquiry <enquiry#website.com>";
PS: Please improve your code formatting.
Try to enter an email at From: in $headers.
Like $headers .= "From: youremail#provider.com" or
$headers .= "From: Website Enquiry <youremail#provider.com>"
And you should change it to
if(mail(...)) {
//success
}
else {
//email failed
}