php - 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}";
}
解决方案
这已经解决了,我把我的变量放在我在 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]);
}
}
}
推荐阅读
- android - 如何在 react-native 中添加 box-shadow?
- python - tkinter 标签中表格结构的 Tkinter 问题
- node.js - MongoDB - 批量查找和 updateOne 无法按预期工作
- javascript - 使用 EJS 的骰子滚轮
- php - 如何在POST方法的下一个php页面上接收从标题(位置:.....)发送的数据?
- python - 使用 Python 仅从 txt 文件中提取所需的列?
- ios - 如何将 AppiumDriver 焦点更改为出现在不同图层上的下拉菜单?iOS
- javascript - JQuery在页面上输出“未定义”
- javascript - Jquery Validation:在提交时验证一个字段一次
- ruby-on-rails - 尝试使用heroku上的rails应用程序从S3获取图像时出现ERR_CERT_COMMON_NAME_INVALID