【问题标题】:Mailer Error: in phpmailer function to send emailMailer 错误:在 phpmailer 函数中发送电子邮件
【发布时间】:2020-11-04 16:13:27
【问题描述】:

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

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

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

<?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}";
}

【问题讨论】:

  • 你能把var_dump($row['attachments']);的结果加起来看看里面的值是什么。
  • 您的分解数组可能包含空值。您可以看到有关如何防止这种情况的答案:stackoverflow.com/questions/3432183/…

标签: php phpmyadmin xampp phpmailer gmail-imap


【解决方案1】:

这已解决,我将我的变量放在我在 if 条件下插入附件值的位置,我检查了数据库中的值不等于 null,文件名我插入数据库中。如果文件名不为空,那么我保存附件的代码将起作用,否则它将不起作用。

  

    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]); 
                    }
                }
            }

【讨论】:

  • 这仅解决了我提到的第一件事(检查您的输入数据)。如果由于某种原因无法读取文件,您仍然会收到异常。
【解决方案2】:

您在 PHPMailer 中启用了异常,并且您调用 addAttachments 时使用了失败的参数(例如 null,或者指向不存在的文件的路径,或者您没有读取权限),所以正如预期的那样,它抛出了一个异常。所以你有两件事要做:找出为什么它无法读取文件,并添加处理它失败的代码,如下所示:

   if($count > 0 && $row['attachments'] != 'null'){
        for ($i=0; $i < $count ; $i++) {
                $file_to_attach = './attachment/' . $array[$i];
                try {
                    $mail->addAttachment($file_to_attach, $array[$i]);
                } catch (Exception $e) {
                    echo "Could not read file $file_to_attach)\n";
                }
        }
    }

此代码允许继续发送 - 是否要执行此操作取决于您。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多