0

I'm trying to send an attachment via email with Phpmailer, but I get the error: Could not access file: pdf_consenso/.
What am I doing wrong ?
File attachments aren't included in the email sent by PHPMailer when submitting the form via AJAX.

Here is the PHP Mailer:

<?php
   
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
   
require 'PHPMailer/Exception.php';
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';

$codPre = $_POST['codPre'];

try {
   if (isset($_FILES['pdf_consenso']['name']) && $_FILES['pdf_consenso']['name'] != "") {
      $file = "pdf_consenso/" . basename($_FILES['pdf_consenso']['name']);
      move_uploaded_file($_FILES['pdf_consenso']['tmp_name'], $file);
   } else
      $file = "";


$mail = new PHPMailer();

$mail->isSMTP(); // Set mailer to use SMTP
$mail->SMTPDebug = 2; // Enable verbose debug output
//$mail->CharSet = 'UTF-8';
$mail->Host = ; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = ; // SMTP username
$mail->Password = ; // SMTP password
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587; // TCP port to connect to

$mail->addAttachment($file);

$mail->setFrom('');
$mail->addAddress(''); // Add a recipient
$mail->Subject = "Consenso Informato - Cod.Prenotazione: " . $codPre;
$mail->Body ="Consenso Informato";
$mail->AltBody = "Consenso Informato";

if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}

echo "<script>alert('Message has been sent')</script>";
}
catch (Exception $e) {
   echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
  }

Here is the contact form :

<form id="uploadFile" enctype="multipart/form-data">
  <div class="field has-addons">
    <p class="control">
      <input class="input" id="codPre" type="text" placeholder="Codice prenotazione">
    </p>
  </div>
  <input type="file" id="pdf_consenso" name="pdf_consenso" hidden>
  <label class="button" for="pdf_consenso">Scegli file</label>
    <span id="file-chosen">Nessun file scelto</span>
  <footer class="modal-card-foot">
    <button type="submit" class="button is-rounded bt-send"><strong>INVIA DOCUMENTO</strong></button>
    <button class="button is-rounded bt-erase">ANNULLA</button>
  </footer>
</form>

Here is AJAX Call:

    // FORM DI CONTATTO - PAGINA DOVE SIAMO
$("#uploadFile").submit(function (event) {
    // cancels the form submission
    event.preventDefault();
    submitForm();
  });
  
  function submitForm() {
     //Initiate Variables With Form Content
     //Creazione di un oggetto FormData…
     var datiForm = new FormData();
     //… aggiunta del nome…
     datiForm.append('codPre',$("#codPre").val());

     //… aggiunta del file
     datiForm.append('pdf_consenso',$('#pdf_consenso')[0].files[0]);
     //Toast messaggio in uscita
     
     iziToast.show({
      color: 'light',
        timeout: false,
      icon: 'fas fa-paper-plane',
      message: '<strong>Invio!</strong></br>Il tuo documento sta per essere inviato...',
      messageLineHeight: 20,
      messageSize: 15,
      position: 'center', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter
      progressBarColor: '#00909D',
      backgroundColor: ' #9ad3ca',
      titleColor: '#222',
      messageColor: '#222',
      iconColor: '#F7F7F7',
      closa: false,
      displayMode: 'once',
      pauseOnHover: false,
      resetOnHover: false,
    });
  
    $.ajax({
      type: "POST",
      url: "fileUpload.php",
      data: datiForm,
      cache: false,
      processData: false,
      contentType: false,
      success: function (data) {
        console.log(data);
        if (data == 'Message sent') {
          iziToast.destroy();
          formSuccess();
        }
      }
    });
  }
  
  function formSuccess() {
    $("#uploadFile")[0].reset();
    // custom toast
    iziToast.show({
      color: 'light',
      icon: 'fas fa-paper-plane',
      message: '<strong>Grazie!</strong></br>Il tuo messaggio è stato inviato',
      messageLineHeight: 20,
      messageSize: 15,
      position: 'center', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter
      progressBarColor: '#00909D',
      backgroundColor: ' #9ad3ca',
      titleColor: '#222',
      messageColor: '#222',
      iconColor: '#F7F7F7',
      closa: false,
      displayMode: 'once',
      pauseOnHover: false,
      resetOnHover: false,
    });
  }
sadek
  • 15
  • 1
  • 6
  • Please try using FormData for `File Upload via AJAX` . See this https://stackoverflow.com/questions/2320069/jquery-ajax-file-upload – Ken Lee Dec 26 '20 at 18:47
  • Take a look at the [file upload example for XHR](https://github.com/PHPMailer/PHPMailer/blob/master/examples/contactform-ajax.phps) provided with PHPMailer. – Synchro Dec 27 '20 at 13:24
  • Thanks, now with formData work. But now I can't get the form to reset and show a correct send message. I have updated the code above – sadek Dec 29 '20 at 17:37

0 Answers0