Search code examples
phpphpmailer

PHPmailer - failing to send if variable $file1 for attachment does not have a value


I have an HTML form that passes indexes to another form, which creates the necessary variables which are then inserted into PHPMailer. One of the options is to browse to a file which is then attached to the email. The problem that I am having is that if there is no file to attach, (then the $file1 variable has "no value") PHPMailer returns the eoor that the message cannot be sent as below - pointing to the directory where the files are stored. Message could not be sent. Mailer Error: Could not access file:C:/wamp64/www/CIA/PODS/

$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
try {
//Server settings
//$mail->SMTPDebug = 2;                                 // Enable verbose debug output
$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'mail.smtp2go.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = '[email protected]';              // SMTP username
$mail->Password = 'xxxxxxxx';                         // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 2525;                                    // TCP port to connect to
//Recipients
$mail->AllowEmpty = true;
$mail->setFrom('[email protected]', 'ICExpress Waybill Updates');
$mail->addAddress('[email protected]'); 
$mail->addAddress($email);  
$mail->addReplyTo('[email protected]');
$mail->addCC($addemail);
$mail->addCC($addemail2);

echo $file1;
$path=$_SERVER['DOCUMENT_ROOT'].'/CIA/PODS/'.$file1;
$name=$file1;
$mail->AddAttachment($path,$name,$encoding ='base64',$type = 'application/octet-stream');
$mail->AllowEmpty = true;
$mail->isHTML(true);                      // Set email format to HTML
$mail->Subject = $subject ;
$mail->Body    = <<<END

Solution

  • You can simply add the attachment if it is available. In case there is no file attachment don't try to add the attachment:

    $path = $_SERVER['DOCUMENT_ROOT'].'/CIA/PODS/'.$file1;
    
    if (is_dir($path) === false && file_exists($path)) {
        $name = $file1;
        $mail->AddAttachment($path, $name, $encoding = 'base64', $type = 'application/octet-stream');
    }
    

    As IncredibleHat also mentioned in the comments you can also use the condition is_file($path) to check the file path like PHPMailer itself:

    if (is_file($path)) {
        $mail->AddAttachment($path, '', $encoding = 'base64', $type = 'application/octet-stream');
    }
    

    You also don't need to specify the name if you want to use the same as specified on path. PHPMailer is using the basename of the path if name parameter is a empty string.