Search code examples
phpemailphpmailer

Could not access file: Could not access file: Could not access file: PHP Mailer issue


Code is working fine without attachments. and attachment code is working fine on another page anybody can help to solve this? <?php

require('phpmailer/class.phpmailer.php');

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = TRUE;
$mail->SMTPSecure = "ssl";
$mail->Port     = 465;  
$mail->Username = "info@guildsconnect.org";
$mail->Password = "Guildsconnect";
$mail->Host     = "webs10rdns1.websouls.net";
$mail->Mailer   = "smtp";
$mail->SetFrom($contact_email, $contact_name);
$mail->AddReplyTo($contact_email, $contact_name);
$mail->AddAddress("hashimbhatti906@gmail.com"); 
$mail->Subject = $sub1;
$mail->WordWrap   = 80;
$mail->MsgHTML($emailbodyis);

foreach ($_FILES["attachment"]["name"] as $k => $v) {
    $mail->AddAttachment( $_FILES["attachment"]["tmp_name"][$k], $_FILES["attachment"]["name"][$k] );
}

$mail->IsHTML(true);

if(!$mail->Send()) {
    $_SESSION["error"] = "Problem in Sending Mail.";
} else {
    $_SESSION["success"] = "Mail Sent Successfully.";
}   

?>

Solution

  • Firstly, you're using a very old and unsupported version of PHPMailer, so upgrade. It also looks like you have based your code on a very old example.

    You are not handling the file upload safely, not validating the uploaded file before trying to use it, as per the PHP docs.

    PHPMailer provides an example that shows how to handle and upload and attach it correctly. The key parts are to use move_uploaded_file() to validate the upload before using it, and not to trust the supplied filename. To paraphrase the example:

        //Extract an extension from the provided filename
        $ext = PHPMailer::mb_pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
        //Define a safe location to move the uploaded file to, preserving the extension
        $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['attachment']['name'])) . '.' . $ext;
    
        if (move_uploaded_file($_FILES['attachment']['tmp_name'], $uploadfile)) {
            //Now create a message
            $mail = new PHPMailer();
    ...
            //Attach the uploaded file
            if (!$mail->addAttachment($uploadfile, 'My uploaded file')) {
                $msg .= 'Failed to attach file ' . $_FILES['attachment']['name'];
            }
            if (!$mail->send()) {
                $msg .= 'Mailer Error: ' . $mail->ErrorInfo;
            } else {
                $msg .= 'Message sent!';
            }
        } else {
            $msg .= 'Failed to move file to ' . $uploadfile;
        }
    

    You don't need to set Mailer yourself; it's already done for you by isSMTP().