I have a PHP contact form that processes submissions via AJAX, but all the emails are landing in Gmail’s spam folder instead of the inbox. I’m not sure what’s causing this issue.
<?php
if($_POST) {
$recipient_email = "[email protected]"; // Replace with your email
// Verify AJAX request
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$response = json_encode(array(
'status':'error',
'message' => 'Request must be sent via AJAX POST'
));
die($response);
}
// Clean input data
$client_name = filter_var($_POST["client_name"], FILTER_SANITIZE_STRING);
$client_email = filter_var($_POST["client_email"], FILTER_SANITIZE_EMAIL);
$area_code = filter_var($_POST["area_code"], FILTER_SANITIZE_NUMBER_INT);
$contact_number = filter_var($_POST["contact_number"], FILTER_SANITIZE_NUMBER_INT);
$email_subject = filter_var($_POST["email_subject"], FILTER_SANITIZE_STRING);
$email_content = filter_var($_POST["content"], FILTER_SANITIZE_STRING);
// Validate form fields
if(strlen($client_name) < 4) {
$response = json_encode(array('status'=>'error', 'message' => 'Name must be at least 4 characters!'));
die($response);
}
if(!filter_var($client_email, FILTER_VALIDATE_EMAIL)) {
$response = json_encode(array('status'=>'error', 'message' => 'Valid email address required!'));
die($response);
}
if(!filter_var($area_code, FILTER_VALIDATE_INT)) {
$response = json_encode(array('status'=>'error', 'message' => 'Area code must contain only numbers'));
die($response);
}
if(!filter_var($contact_number, FILTER_SANITIZE_NUMBER_FLOAT)) {
$response = json_encode(array('status'=>'error', 'message' => 'Phone number must contain only digits'));
die($response);
}
if(strlen($email_subject) < 3) {
$response = json_encode(array('status'=>'error', 'message' => 'Subject field is required'));
die($response);
}
if(strlen($email_content) < 3) {
$response = json_encode(array('status'=>'error', 'message' => 'Message content is too short!'));
die($response);
}
// Build email content
$full_message = $email_content."\r\n\r\n-".$client_name."\r\nEmail: ".$client_email."\r\nPhone: (".$area_code.") ". $contact_number;
// Set email headers
$email_headers = 'From: '.$client_name.'' . "\r\n" .
'Reply-To: '.$client_email.'' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
$mail_sent = mail($recipient_email, $email_subject, $full_message, $email_headers);
if(!$mail_sent) {
$response = json_encode(array('status'=>'error', 'message' => 'Mail delivery failed! Check PHP mail settings.'));
die($response);
} else {
$response = json_encode(array('status'=>'success', 'message' => 'Hello '.$client_name.', thanks for contacting us!'));
die($response);
}
}
?>
The form seems to have proper validation and headers set up. Has anyone dealt with this Gmail spam issue before? I’ve tried various solutions but nothing seems to work. Any suggestions would be really helpful!