首页 > 解决方案 > Mailer 错误:在 phpmailer 函数中发送电子邮件

问题描述

当我使用简单的正文发送不带附件的电子邮件时,我收到无法发送消息的错误。邮件程序错误:无法访问文件:./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}";
}

标签: phpphpmyadminxamppphpmailergmail-imap

解决方案


这已经解决了,我把我的变量放在我在 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]); 
                    }
                }
            }


推荐阅读