PHP mail() contact form not delivering to Gmail - advice needed - php

I'm using a PHP contact form and it is sending mail to non gmail addresses, however when I set it to send to a gmail address, it doesn't get delivered (it doesn't even appear in junk mail).
I've heard of issues like this before - I'm not a web developer/expert so can anybody suggest code/configuration changes to my PHP contact form below which would essentially mean messages get delivered to gmail addresses?
I'm on a linux/WHM dedicated server.
<?php
error_reporting(E_NOTICE);
function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
if(!empty($_POST['name']) && !empty($_POST['email']) && valid_email($_POST['email']) === true && !empty($_POST['comment']))
{
$to = "contactform#gmail.com";
$headers = 'From: '.$_POST['email'].''. "\r\n" .
'Reply-To: '.$_POST['email'].'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$subject = "Contact Form";
$message = htmlspecialchars($_POST['comment']);
if(mail($to, $subject, $message, $headers))
{
echo 1; //SUCCESS
}
else {
echo 2; //FAILURE - server failure
}
}
else {
echo 3; //FAILURE - not valid email
}
?>

Did you check to see if your PHP installation/server supports the Mail() function?
Also did you check to see if Gmail is treating your emails as spam? (they wont show up in the spam folder, they are just blocked)... Try sending it to a different address.

Set your script to send it from an email address that has an actual mailbox somewhere so you can check for bounces. If your script echoing 1, and can send to other addresses it suggests (to me at least), that it's gmail not liking you, rather than anything wrong with the script per se.
It also looks like you need to look into protecting this script from email injection. Just a suggestion though.

Related

Why is PHP's mail function failing to deliver intermittently? [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
I have an event that fires every time a user successfully submits a form on my website. I can track the exact time that the event fired from my Google Analytics account. The time that the event fired, mirrors the delivery time of the email delivered to my inbox (yahoo mail).
However, I've noticed many times that, when the same event fires, no email is delivered to the the same email address. It never reaches its destination.
How can I fix this? What is the root of this problem?
Here is my php code:
<?php
if($_POST)
{
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
die();
}
//check $_POST vars are set, exit if any missing
if(!isset($_POST["userName"]) || !isset($_POST["userLastName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userArrival"]) || !isset($_POST["userNumberPeople"])
|| !isset($_POST["userPickupLocation"]) || !isset($_POST["userRequest"]) || !isset($_POST["userTourSelection"]))
{
die();
}
//Sanitize input data using PHP filter_var().
$user_Name = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
$user_LastName = filter_var($_POST["userLastName"], FILTER_SANITIZE_STRING);
$user_Email = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
$user_TourSelection = filter_var($_POST["userTourSelection"], FILTER_SANITIZE_STRING);
$user_Arrival = filter_var($_POST["userArrival"], FILTER_SANITIZE_STRING);
$user_NumberPeople = filter_var($_POST["userNumberPeople"], FILTER_SANITIZE_STRING);
$user_PickupLocation = filter_var($_POST["userPickupLocation"], FILTER_SANITIZE_STRING);
$user_Request = filter_var($_POST["userRequest"], FILTER_SANITIZE_STRING);
$to_Email = "something#yahoo.com"; //Replace with recipient email address
$subject = 'Tour request: '.$user_TourSelection.' '; //Subject line for emails
//additional php validation
if(strlen($user_Name)<2) // If length is less than 4 it will throw an HTTP error.
{
header('HTTP/1.1 500 Name is too short or empty!');
exit();
}
if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
{
header('HTTP/1.1 500 Please enter a valid email address!');
exit();
}
if(strlen($user_Request)<5) //check emtpy message
{
header('HTTP/1.1 500 Please explain in a few words how you would like us to assist you.');
exit();
}
// message
$message = '<strong>Name:</strong> '.$user_Name.' '.$user_LastName.' <br><br>
<strong>Date of Arrival:</strong> '.$user_Arrival.' <br><br>
<strong>Tour:</strong> '.$user_TourSelection.' <br><br>
<strong>Number of people:</strong> '.$user_NumberPeople.' <br><br>
<strong>Pick-Up Location:</strong> '.$user_PickupLocation.' <br><br>
<strong>Request:</strong> '.$user_Request.'
';
//proceed with PHP email.
$headers = 'From: '.$user_Email.'' . "\r\n" .
$headers .='Reply-To: '.$user_Email.'' . "\r\n" ;
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .='X-Mailer: PHP/' . phpversion();
#$sentMail = mail($to_Email, $subject, $message, $headers);
if(!$sentMail)
{
header('HTTP/1.1 500 Our server is under maintenance!<br> If this error persists please contact us directly: <strong>something#yahoo.com</strong>');
exit();
}else{
echo 'Congratulations '.$user_Name .'! ';
echo 'We have received your request and we will respond as soon as possible.';
}
}
?>
mail()'s delivery function ends when it hands off your mail to the SMTP server. Its sole responsibility is the real-world equivalent of taking your envelope and dropping it into the mailbox on the corner. The rest of the postal service (emptying that box, running it through processing centers, flying it to the recipient's country/city, etc...) is completely outside of mail()'s scope. As long as the envelope drops into the mailbox, mail() will return true and pretend it was delivered.
So... check your SMTP server's logs to see what really happened to the mail. Maybe it got marked as spam by the receiver and bounced. Maybe it's stuck in a queue somewhere, etc... Only the logs will tell you this - anything you can see/do in PHP is useless, because PHP and mail() only do maybe 1% of the email sending/delivery process, and something's wrong in that other 99%.

Do I need to configure my Nginx server to send PHP mails?

I am trying to send an email through php. But the mail() function keeps returning FALSE even though I am sure everything is correct.
After browsing through stackoverflow for similar problems, one answer stood out by saying that it could also be because of the server.
NOTE: The mail server part of the nginx server isn't configured yet. I have no idea if PHP needs that specific module in order to work.
# $email and $randomPassword already defined.
$subject = "New Password";
$message = "Your new password is ".$randomPassword;
$headers = 'From: contact#mail.com' . "\r\n" .
'Reply-To: contact#email.com';
$checkMail = mail($email, $subject, $message, $headers);
if ($checkMail) {
echo "Mail send";
} else {
echo "Mail not send";
}

PHP - Sending email from form with mail function

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.

Sending mail via php and from headers?

When I send mail from my php script I send it like so
$to = $_POST['email'];
$subject = $_POST['username'] . ' - Validate your account at example.com!';
$message = 'http://www.example.com/activate?username=' . $_POST['username'] . '&code=' . $random;
$headers = 'From: noreply#example.com';
When the mail comes through to an email the from header shows like this,
noreply#example.com via web87.extendcp.co.uk
Is there a way I can stop the via bit from showing?
The only solution would be to use your own SMTP server, or at least another one... If your provider allows that.
It is your provider's web server which modifies the From: line here.
Yes, you need to implement DKIM signing of your e-mails so Gmail can verify that your server has the right to send e-mail for that domain.
Try using the IMAP-method from PHP
First connect with the GMail imap-server:
http://www.php.net/manual/en/function.imap-open.php
(Make sure you're using SSL/TLS)
Then send the message with imap_mail():
http://www.php.net/manual/en/function.imap-mail.php
$host="{imap.gmail.com:993/imap/ssl/novalidate-cert}";
$user=""; // Your GMail-account
$pass=""; // Your GMail-password
if ($mbox=imap_open($host, $user, $pass)) {
// Connection Success
$to = "";
$subject = "";
$headers = "";
imap_mail ($to, $subject, $message, $headers)
} else {
// Failed to connect
}
Hope this helps ;)
While fge's answer is most likely the correct one here, there's always a chance that your server's mail service won't add it if there's a "friendly" name in the header:
From: No Reply <noreply#example.com>
...instead of just:
From: noreply#example.com

Why is my AJAX Form Not Sending Email?

I am using a PHP Mail form with AJAX and it's not sending any mail. What am I missing here?
send.php
<?php
error_reporting(E_NOTICE);
function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
if($_POST['first_name']!='' && $_POST['last_name']!='' && $_POST['e_mail']!='' && valid_email($_POST['e_mail'])==TRUE && strlen($_POST['message'])>30)
{
$to = 'zacharyrs#gmail.com';
$headers = 'From: '.$_POST['e_mail'].''. "\r\n" .
'Reply-To: '.$_POST['e_mail'].'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$subject = "Hello! I'm testing my new ajax email that I got from roscripts.com";
$message = htmlspecialchars($_POST['message']);
if(mail($to, $subject, $message, $headers))
{//we show the good guy only in one case and the bad one for the rest.
echo 'Thank you '.$_POST['first_name'].'. Your message was sent';
}
else {
echo "Message not sent. Please make sure you're not
running this on localhost and also that you
are allowed to run mail() function from your webserver";
}
}
else {
echo 'Please make sure you filled all the required fields,
that you entered a valid email and also that your message
contains more then 30 characters.';
}
?>
Is your email setup in PHP? Check that first, otherwise there doesn't seem to be any issue here that I can see. You should get some kind of output from this if/else block.
I would start by reviewing PHP error logs, to see if your mail() fn is working. That may be the cause.

Categories