邮件程序错误:在 phpmailer 函数中发送电子邮件

当我过去使用简单文本正文发送不带附件的电子邮件时,出现消息无法发送的错误。邮件程序错误:无法访问文件:./attachment/

如果我评论我的附件功能,我的代码工作正常。

$mail->send 函数每次都会尝试搜索附件文件夹。即使文件不存在于电子邮件中,即文件仅包含文本。

https://img3.mukewang.com/64cf3e790001015804210171.jpg

<?php

    

include('db.php');

use PHPMailer\PHPMailer\PHPMailer;

use PHPMailer\PHPMailer\Exception;

require_once "vendor/autoload.php";

    

$id = $_GET['id'];

    

$query = "select * from access where uid='$id'";

$result = mysqli_query($conn,$query);

$row = mysqli_fetch_assoc($result);

    

$mail = new PHPMailer(true);

    

try {  

    

  $mail->setFrom('sender@gmail.com');

  $mail->addAddress('receiver@gmail.com');

    

  $array = explode(", ",$row['attachments']);

  $count = count($array);

  if($count > 0 && $row['attachments'] != 'null'){

    for ($i=0; $i < $count ; $i++) {

      $file_to_attach = './attachment/' . $array[$i];

      $mail->addAttachment($file_to_attach, $array[$i]); 

    }

  }

    

  $mail->isHTML(true);                                  

  $mail->Subject = $row['subject'];

  $mail->Body    = $row['body'];

    

  $mail->send();

  echo 'Message has been sent';

} catch (Exception $e) {

  echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";

}


慕运维8079593
浏览 127回答 2
2回答

白衣染霜花

您在 PHPMailer 中启用了异常,并且使用addAttachments失败的参数进行调用(例如 null,或不存在的文件路径,或者您没有读取权限),因此它会抛出异常,如下所示预期的。因此,您需要做两件事:找出它无法读取文件的原因,并添加处理失败的代码,如下所示:&nbsp; &nbsp;if($count > 0 && $row['attachments'] != 'null'){&nbsp; &nbsp; &nbsp; &nbsp; for ($i=0; $i < $count ; $i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $file_to_attach = './attachment/' . $array[$i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $mail->addAttachment($file_to_attach, $array[$i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (Exception $e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; echo "Could not read file $file_to_attach)\n";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }该代码允许发送无论如何继续 - 这取决于您是否愿意这样做。

侃侃尔雅

    if($row['attachments']!=null)             {                $array = explode(", ",$row['attachments']);                $count = count($array);                if($count > 0 && $row['attachments'] != 'null'){                    for ($i=0; $i < $count ; $i++) {                            $file_to_attach = './attachment/' . $array[$i];                            $mail->addAttachment($file_to_attach, $array[$i]);                     }                }            }
打开App,查看更多内容
随时随地看视频慕课网APP