首页 > 解决方案 > 来自邮件功能的邮件在垃圾邮件中

问题描述

我正在使用以下代码发送电子邮件,但不幸的是电子邮件进入垃圾邮件。检查代码并需要建议...我正在使用 php mail() 函数发送邮件..我犯了什么错误?代码是否正确?邮件正在发送,但进入垃圾邮件而不是收件箱。所以我需要在我的代码中更正..

<?php
class mail
{
    function setInput($data)
    {
        $data = trim($data);
        $data = addslashes($data);
        $data = htmlspecialchars($data);
        return $data;
    }
    public function send($data)
    {
            $email_to = "xyz@gmail.com";
        $email_subject=$this->setInput($data['Subject']);

        $phone = $this->setInput($data['Phone']); // required
        $email = $this->setInput($data['Email']); // required
        $name = $this->setInput($data['Name']); // not required
        $message = $this->setInput($data['Message']); // required

         $error_message = "";
         $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';

         if(!preg_match($email_exp,$email)) {
        $error_message .= 'The Email Address you entered does not appear to be valid.<br />';
        }
 
        $string_exp = "/^[A-Za-z .'-]+$/";
 
       if(!preg_match($string_exp,$name)) {
         $error_message .= 'The First Name you entered does not appear to be valid.<br />';
         }
 
        if(strlen($message) < 2) {
         $error_message .= 'The Comments you entered do not appear to be valid.<br />';
         }
 
        if(strlen($error_message) > 0) {
           died($error_message);
         }
 
        $email_message = "Form details below.\n\n";
 
     
         function clean_string($string) {
           $bad = array("content-type","bcc:","to:","cc:","href");
          return str_replace($bad,"",$string);
         }

        $email_message .= "Subject: ".clean_string($email_subject)."\n";
        $email_message .= "Email: ".clean_string($email)."\n";
        $email_message .= "Name: ".clean_string($name)."\n";
        $email_message .= "Comments: ".clean_string($message)."\n";

        $headers = 'From: '.$email."\r\n".
       'Reply-To: '.$email."\r\n" .
       'X-Mailer: PHP/' . phpversion();
        @mail($email_to, $email_subject, $email_message, $headers); 

        echo "<script>
          alert('Thank you for contacting us. We will be in touch with you very soon.');
           window.location.href='contact.php';
           </script>";

    }
}
$objclass=new mail();

if(isset($_REQUEST['page_action']))
{
   $page_action=$_REQUEST['page_action'];
   switch($page_action)
   {
      case "email-msg";
      $objclass->send($_POST);
      break;
   }
}

?>

标签: php

解决方案


请检查

  1. 您的服务器(运行此 PHP 脚本)是否有反向 DNS 记录(PTR 记录)

  2. 发件人电子邮件 ($email) 是否已设置为具有 SPF 记录,指定此服务器 IP 为电子邮件的合法来源。(例如,在您的域 DNS 记录中使用 TXT 记录,例如 v=spf1 ip4:xxxx a mx ptr ~all,其中 xxxx 是运行 PHP 脚本的服务器的 IP)

您还需要检查此服务器的 IP 是否已被列入垃圾邮件来源黑名单。但是请先检查上面的1和2。

另一种解决方案是通过 SMTP 服务器发送邮件。您可以使用 PhpMailer 来帮助您完成此操作(https://github.com/PHPMailer/PHPMailer)。如果您的 SMTP 服务器配置正确(并且未被列入垃圾邮件来源黑名单),则发出的邮件将到达收件人收件箱,但不会到达垃圾邮件文件夹。


推荐阅读