When i used to send email without attachments with simple text body, i got an error with Message could not be sent. Mailer Error: Could not access file: ./attachment/
if i comment my function for attachment, my code is working fine.
$mail->send function try to search for attachment folder every time. even if file is not present in the email i.e file is contains only text.
<?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}";
}
You have enabled exceptions in PHPMailer, and you're calling addAttachments
with parameters that fail (e.g. null, or a path to a file that doesn't exist, or you don't have permission to read), so it's throwing an exception, as expected. So you have two things to do: figure out why it can't read the file, and add code that deals with it failing, like this:
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";
}
}
}
This code allows the send to continue anyway – it's up to you whether that' s what you want to do or not.