0

I make a simple contact form for WordPress using ajax and php mail() but my maximum mail is going to spam folder. what is wrong with my code? or any other solution ? like SMTP.

<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
    $errorMSG = "Name is required ";
} else {
    $name = $_POST["name"];
}

// EMAIL
if (empty($_POST["email"])) {
    $errorMSG .= "Email is required ";
} else {
    $email = $_POST["email"];
}

// Subject
if (empty($_POST["subject"])) {
    $errorMSG .= "Subject is required ";
} else {
    $subject = $_POST["subject"];
}

// MESSAGE
if (empty($_POST["message"])) {
    $errorMSG .= "Message is required ";
} else {
    $message = $_POST["message"];
}

//receiver email address
$EmailTo = "info@mydomain.com";

$Subject = $subject;
$form  =  $name;
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";

// send email
$headers  = "From: " .($email) . "\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/html; charset=ISO-8859-1\r\n";
$headers .= "X-Priority: 3\r\n";
$headers .= "X-Mailer: PHP". phpversion() ."\r\n";
// send email
$success = mail($EmailTo, $Subject, $Body, $headers);


// redirect to success page
if ($success && $errorMSG == ""){
   echo "success";
}else{
    if($errorMSG == ""){
        echo "Something went wrong :(";
    } else {
        echo $errorMSG;
    }
}
Firefog
  • 3,094
  • 7
  • 48
  • 86
  • Yes, you should go with SMTP. Also, instead of struggling with the low-level `mail()` function, I would recommend to use one of the tried and tested mail libraries, like PHPMailer, SwiftMailer etc instead. That doesn't just give you a more verbose API, it also makes your code more portable since they don't depend on any server configuration (at least not when using SMTP), – M. Eriksson Sep 30 '18 at 11:41
  • @MagnusEriksson thanks for the clarification can you help me to write my code for PHPMailer ? I already install it – Firefog Sep 30 '18 at 12:06
  • Just read the documentation. It's easy enough and they have really good examples. – M. Eriksson Sep 30 '18 at 12:09

1 Answers1

0

There are multiple reasons for emails treated as spam. Usually it relates to the server sending the mail, apart from content or headers of the mail itself. E.g. the DNS might be not configured correctly, there are some tools in the web that might support you troubleshoot, unfortunately I don't find the tool I used some years ago. Google might bring you up some tools for checking the DNS configuration. There was already some discussion on stackoverflow about this topic, please check this thread to avoid a duplicate discussion.

I recommend using a library like PHPMailer for handling mails.

asattler
  • 59
  • 5