【问题标题】:PHP Mail Without STMP: mail() and PHPMailer Echo Failure upon Send没有 SMTP 的 PHP 邮件:mail() 和 PHPMailer 发送时回显失败
【发布时间】:2020-05-20 18:15:14
【问题描述】:

我正在尝试从托管在 BlueHost 上的我们网站发送一封包含附件的电子邮件。我们发现,截至 2015 年 8 月,我们的原始脚本将不再向我们的邮箱发送电子邮件。

快进到现在,我们正在尝试解决此电子邮件问题,但没有成功。最初,我们的代码使用旧的 mail() 方法。以下是对这种方法的尝试修复(不返回 PHP/日志错误):

<?php
if(!isset($_POST["email"]) && !isset($_POST["name"]))
{
    echo "Error: Form Not Submitted.\n Name and email are mandatory!Please Click the back button to return to the website.\n";
    //Set Variables
    $company = $_POST["company"];
    $address = $_POST["address"];
    $phone = $_POST["phone"];
    $name = $_POST["name"];
    $position = $_POST["position"];
    $visitor_email = $_POST["email"];
    $message = $_POST["message"];
    $submitVar = $_POST["submit"];
    echo "$company, $address, $phone, $name, $position, $visitor_email, $message \r\n";
}
else{
    //Set Variables
    $company = $_POST["company"];
    $address = $_POST["address"];
    $phone = $_POST["phone"];
    $name = $_POST["name"];
    $position = $_POST["position"];
    $visitor_email = $_POST["email"];
    $message = $_POST["message"];
    echo "$company, $address, $phone, $name, $position, $visitor_email, $message \r\n";

    if(IsInjected($visitor_email))
    {
        echo "Bad email value!";
        exit;
    }

    //***Lay out Message***//   
    $to = "example@att.net";
    $email_from = $visitor_email;
    $email_subject = "Website Form Submission from $company";
    $email_body = "Dear Email Target,\n\n $message\n\nSincerely,\n\n$name\n$position\n\n$company\n$address\n$phone";

    //***Attatch the file***//
    $filename = $_FILES['attachment1']['tmp_name'];
    $filetype = $_FILES['attachment1']['tmp_type'];
    $filesize = $_FILES['attachment1']['tmp_size'];  // get size of the file for size validation
    if($filesize > 0){
        $handle = fopen($filename, "r");
        $content = fread($handle, $filesize);
        fclose($handle);
        $attachment = chunk_split(base64_encode($content));
    }

    //*** Establish Boundary ***//  
    $boundary = md5(date('r', time()));

    //***Start Header***//
    $headers = "MIME-Version: 1.0\r\n";
    $headers = "X-Mailer: PHP/" . phpversion()."\r\n";
    $headers .= "From: ".$name." <".$email_from.">\r\n";
    $headers .= "To: ".$email."\r\n";
    $headers .= "Subject: $email_subject\r\n";
    $headers .= "Reply-To: ".$visitor_email."\r\n";
    $headers .= "Content-Type: multipart/mixed"; 
    $headers .= "boundary = \"".$boundary."\"\r\n\r\n";

    //***Message Section***//
    $body = "--$boundary\r\n"; 
        $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n"; 
        $body .= "Content-Transfer-Encoding: base7\r\n\r\n";  
        $body .= $email_body;

    //***Attachment Section***//;
    if($filesize > 0){
        $body .= "--$boundary\r\n"; 
        $body .="Content-Type:".$filetype."; name=\"".$filename."\"\r\n"; 
        $body .="Content-Disposition: attachment; filename=".$filename."\r\n"; 
        $body .="Content-Transfer-Encoding: base64\r\n"; 
        $body .="X-Attachment-Id: ".rand(1000, 99999)."\r\n\r\n";  
        $body .= $attachment."\r\n\r\n"; // Attaching the encoded file with email 
    }

    //***End Email***///
    $body .= "--$boundary--";

    //Send the email!
    $test = mail($to, $email_subject, $body, $headers);
    if($test){
        echo "TRUE";
        //done. redirect to thank-you page.
        header("Location: ./Sales_Quotes.html"); 
        echo '<h5 class="contentHeader simple">Form Submitted!</h5>';
        /* Redirect browser */
        exit();/*Good Practice*/
    } else {
        die("Error: PHP mail() failure!\r\n"
        .$to."\r\n"
        .$email_subject."\r\n"
        .$body."\r\n"
        .$headers."\r\n");
    }
}

// Function to validate against any email injection attempts
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;
    }
}
?> 

运行 Debian 10.2 的 localhost 和 BlueHost 都告诉我 mail() 函数在我调用它时失败。我哪里做错了?由于我在工作 2 天后对此毫无进展,因为每个人似乎都希望我使用 PHPMailer,我还使用 PHPMailer 方法创建了第二个脚本,它也以完全相同的方式失败(没有日志/php 错误,告诉我呼叫失败):

<?php
require_once './PHPMailer.php';
require_once './Exception.php';
use PHPMailer\PHPMailer\PHPMailer;
if(!isset($_POST["email"]) && !isset($_POST["name"]))
{
    echo "Error: Form Not Submitted.\n Name and email are mandatory!Please Click the back button to return to the website.\n";
    //Set Variables
    $company = $_POST["company"];
    $address = $_POST["address"];
    $phone = $_POST["phone"];
    $name = $_POST["name"];
    $position = $_POST["position"];
    $visitor_email = $_POST["email"];
    $message = $_POST["message"];
    $submitVar = $_POST["submit"];
    echo "$company, $address, $phone, $name, $position, $visitor_email, $message \r\n";
}
else{
    //***Set Variables***//
    $company = $_POST["company"];
    $address = $_POST["address"];
    $phone = $_POST["phone"];
    $name = $_POST["name"];
    $position = $_POST["position"];
    $visitor_email = $_POST["email"];
    $message = $_POST["message"];
    echo "$company, $address, $phone, $name, $position, $visitor_email, $message \r\n";

    if(IsInjected($visitor_email))
    {
        echo "Bad email value!";
        exit;
    }

    //***Lay out Message***//   
    $to = "example@att.net";
    $email_from = $visitor_email;
    $email_subject = "Website Form Submission from $company";
    $email_body = "Dear Target,\n\n $message\n\nSincerely,\n\n$name\n$position\n\n$company\n$address\n$phone";

    //***Upload the file***//
    $filename = $_FILES['attachment1']['tmp_name'];
    $filetype = $_FILES['attachment1']['type'];
    $filesize = $_FILES['attachment1']['size'];  // get size of the file for size validation
    if($filesize > 0){
        $attachment = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['attachment1']['name']));
        if (!(move_uploaded_file($_FILES['attachment1']['tmp_name'], $uploadfile))){
            echo "Failed to Upload File Properly.";
        }
    }

    //***Create the PHPMailer Message***//:
    $mail = new PHPMailer(true);
    $mail -> setFrom($email_from,$name);
    $mail -> To = "sietins@sietins.com";
    $mail -> addAddress("example@att.net", "Mr. Example");
    $mail -> Subject = $email_subject;
    $mail -> Body = $email_body;
    if($filesize > 0){
        //***Attach the file***//
        $mail ->addAttachment($uploadfile,$filename);
    }

    //***Send the email!***//
    if(!$mail->send()){
        echo "TRUE";
        //done. redirect to thank-you page.
        header("Location: ./Sales_Quotes.html"); 
        echo '<h5 class="contentHeader simple">Form Submitted!</h5>';
        /* Redirect browser */
        exit();/*Good Practice*/
    } else {
        die("Error: PHP mail() failure!\r\n"
        .$to."\r\n"
        .$email_subject."\r\n"
        .$email_body."\r\n");
    }
}

// Function to validate against any email injection attempts
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;
    }
}
?> 

是否有任何满足以下要求的简单解决方案/更正?:

  • 没有 SMTP。本地主机首选。
  • 快速/轻松设置
  • 必须支持 可选附件来自用户
  • 必须适用于 BlueHost。

请注意,这适用于制造业中的小型企业。 我已经束手无策了,我已经在这上面花了太多时间。任何帮助将不胜感激。

【问题讨论】:

  • 一方面,您在标题之前输出。启用错误报告,检查它们是什么,然后重新开始。
  • mail() 函数的许多问题之一是,它确实没有给你任何关于它可能失败的原因的反馈。查找您的消息发生了什么的地方是您的本地邮件服务器的日志文件。鉴于所有邮件函数所做的只是调用一个打开与本地主机的同步 SMTP 连接的 sendmail 二进制文件,您应该会发现直接从 PHPMailer 到本地主机的 SMTP 更快且更容易诊断(因为您可以启用SMTPDebug)。此外,您没有收到任何错误消息,因为您没有打印!如果您的发送失败,请回显$mail-&gt;ErrorInfo
  • @Synchro:添加了$mail-&gt;ErrorInfo;,除了我已经输出的内容之外没有其他输出。它只是失败了。
  • 您要求 PHPMailer 抛出异常(通过将 true 传递给构造函数),但您没有围绕它的 try/catch 块,因此您的脚本将终止(带有致命的未捕获异常)只要你调用send(),无论成功还是失败,它都不会到达你的echo 输出。
  • try{ if(!$mail-&gt;send()){ echo "TRUE"; //done. redirect to thank-you page. header("Location: ./Sales_Quotes.html"); echo '&lt;h5 class="contentHeader simple"&gt;Form Submitted!&lt;/h5&gt;'; /* Redirect browser */ exit();/*Good Practice*/ } else { die("Error: PHP mail() failure!\r\n" ."\r\n"); echo $mail-&gt;ErrorInfo; } } catch (phpmailerException $e) { echo $e-&gt;errorMessage(); //PHPMailer error messages } catch (Exception $e) { echo $e-&gt;getMessage(); // other error messages } 你的意思是这样吗?刚刚试了,还是没有错误。

标签: php email localhost phpmailer bluehost


【解决方案1】:

经过大量的测试和调试,最终的代码如下:

<?php
require_once './PHPMailer.php';
require_once './Exception.php';
use PHPMailer\PHPMailer\PHPMailer;
if(!isset($_POST["email"]) && !isset($_POST["name"]))
{
    echo "Error: Form Not Submitted.\n Name and email are mandatory! Please Click the back button to return to the website.\n";
    //Set Variables
    $company = $_POST["company"];
    $address = $_POST["address"];
    $phone = $_POST["phone"];
    $name = $_POST["name"];
    $position = $_POST["position"];
    $visitor_email = $_POST["email"];
    $message = $_POST["message"];
    $submitVar = $_POST["submit"];
    echo "$company, $address, $phone, $name, $position, $visitor_email, $message \r\n";
}
else{
    //***Set Variables***//
    $company = $_POST["company"];
    $address = $_POST["address"];
    $phone = $_POST["phone"];
    $name = $_POST["name"];
    $position = $_POST["position"];
    $visitor_email = $_POST["email"];
    $message = $_POST["message"];
    //echo "$company, $address, $phone, $name, $position, $visitor_email, $message \r\n";

    if(IsInjected($visitor_email))
    {
        echo "Bad email value!";
        exit;
    }

    //***Lay out Message***//   
    $to = "example@att.net";
    $email_from = $visitor_email;
    $email_subject = "Website Form Submission from $company";
    $email_body = "Dear Target Company,\n\n $message\n\nSincerely,\n\n$name\n$position\n\n$company\n$address\n$phone";

    //***Upload the file***//
    $filename = $_FILES['attachment1']['tmp_name'];
    $filetype = $_FILES['attachment1']['type'];
    $filesize = $_FILES['attachment1']['size'];  // get size of the file for size validation
    if($filesize > 0){
        $attachment = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['attachment1']['name']));
        if (!(move_uploaded_file($_FILES['attachment1']['tmp_name'], $uploadfile))){
            echo "Failed to Upload File Properly.";
        }
    }

    //***Create the PHPMailer Message***//:
    $mail = new PHPMailer(true);
    $mail -> setFrom($email_from,$name);
    $mail -> To = "example@att.net";
    $mail -> addAddress("example@att.net", "Mr Example");
    $mail -> Subject = $email_subject;
    $mail -> Body = $email_body;
    if($filesize > 0){
        //***Attach the file***//
        $mail ->addAttachment($uploadfile,$filename);
    }

    //***Send the email!***//
    try{
        $mail->send();
        //done. redirect to thank-you page.
        header("Location: ./Sales_Quotes.html"); 
        echo '<h5 class="contentHeader simple">Form Submitted!</h5>';
        /* Redirect browser */
        exit();/*Good Practice*/
    }
    catch (phpmailerException $e) {
        echo "Error: PHPMailer failure!: ";
        echo $e->errorMessage();  //PHPMailer error messages
        echo $mail->ErrorInfo;
    }
    catch (Exception $e) {
        echo "Error: PHPMailer failure!: ";
        echo $e->getMessage();  // other error messages
        echo $mail->ErrorInfo;
    }
}

// Function to validate against any email injection attempts
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;
    }
}
?> 

事实证明,PHPMailer 的许多示例和答案都是错误输入或错误引用。对于希望不使用 SMTP 并包含附件的任何人,此代码应该可以在 BlueHost 上工作(最少发送电子邮件)。

【讨论】:

    【解决方案2】:

    把它放在邮件输出的开头和结尾: Ob_start(); ob_end_clean();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-10
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      • 2015-08-27
      • 1970-01-01
      • 2017-05-19
      相关资源
      最近更新 更多