6

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>';
}
user1040259
  • 6,369
  • 13
  • 44
  • 62
  • I don't know the answer 'why' it happens but I have an idea. Send yourself an email in a normal way, check its raw contents, and then check the contents of the email you send using your php. SOmething is probably missing. – Grzegorz Aug 30 '12 at 00:30
  • 1
    it may well just be the nature of your message. there's no magic header that will make an email never be marked as spam . –  Aug 30 '12 at 00:30
  • 3
    Erroneous headers are not the only reason messages get filed as spam. Other issues like the content, the reverse DNS lookups performed on the sending host, and others all contribute. – Michael Berkowski Aug 30 '12 at 00:31
  • Use PHPMailer and a Gmail account to use SMTP, assuming the contents of the message is not spam this should avoid spam filters. http://forums.digitalpoint.com/showthread.php?t=871893 – Joel Aug 30 '12 at 00:36

4 Answers4

13

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>");
  }
iHaveacomputer
  • 1,427
  • 4
  • 14
  • 30
Erfan Safarpoor
  • 5,109
  • 4
  • 23
  • 27
4

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"!

iHaveacomputer
  • 1,427
  • 4
  • 14
  • 30
0

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"

Antoine
  • 800
  • 3
  • 14
  • 29
DevWL
  • 17,345
  • 6
  • 90
  • 86
0

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>';
        }
    }
?>
Ludolfyn
  • 1,806
  • 14
  • 20