0

i have a working phpmailer contact form on my website, now i want to be able to attach files to the mail and be able to send it but i dont know how to POST the data.

this is the script on my html

  $(document).ready(function (e){
      $("#contactForm").on('submit',(function(e){
          e.preventDefault();
          $('#boton').hide();
          $('#loader-icon').show();
          $.ajax({
              url: "curriculum.php",
              type: "POST",
              dataType:'json',
              data: {
                  "nombre":$('input[name="nombre"]').val(),
                  "fecha":$('input[name="fecha"]').val(),
                  "correo":$('input[name="correo"]').val(),
                  "ocupacion":$('input[name="ocupacion"]').val(),
                  "domicilio":$('input[name="domicilio"]').val(),
                  "telefono":$('input[name="telefono"]').val(),
                  "nacionalidad":$('input[name="nacionalidad"]').val(),
                  "salario":$('input[name="salario"]').val(),
                  "mensaje":$('input[name="mensaje"]').val()},              
              success: function(response){  
                      alert(response.text);
              },
              error: function(){
                alert(response.text);
              } 
          });
      }));
  });

with this script i feed this next php and my emails are sent right now i have manually set the attachment for the mail but obviously i want to remove that line and be able to upload ht file from the web site

<?php
  use PHPMailer\PHPMailer\PHPMailer;
  use PHPMailer\PHPMailer\Exception;

  require 'phpmailer/Exception.php';
  require 'phpmailer/PHPMailer.php';
  require 'phpmailer/SMTP.php';


  $mail = new PHPMailer(true); // Passing `true` enables exceptions
  try {
  //Server settings
  $mail->isSMTP();           // Set mailer to   use SMTP
  $mail->Host = '****'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = '****';                 // SMTP username
$mail->Password = '****';                           // SMTP password
$mail->SMTPSecure = '****';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = ****;                                    // TCP port to connect to

//Recipients
$mail->setFrom('noreply@nautilusagency.com');
$mail->addAddress('ontiverosmtz.alberto@gmail.com');

$user_name      = filter_var($_POST["nombre"], FILTER_SANITIZE_STRING);
$user_fecha     = filter_var($_POST["fecha"], FILTER_SANITIZE_STRING);
$user_email     = filter_var($_POST["correo"], FILTER_SANITIZE_EMAIL);
$user_ocupacion     = filter_var($_POST["ocupacion"], FILTER_SANITIZE_STRING);
$user_domicilio      = filter_var($_POST["domicilio"], FILTER_SANITIZE_STRING);
$user_telefono     = filter_var($_POST["telefono"], FILTER_SANITIZE_STRING);
$user_nacionalidad      = filter_var($_POST["nacionalidad"], FILTER_SANITIZE_STRING);
$user_salario     = filter_var($_POST["salario"], FILTER_SANITIZE_STRING);
$content   = filter_var($_POST["mensaje"], FILTER_SANITIZE_STRING);
$mail->addAttachment('assets/pagina.zip');
//Content

$mail->isHTML(true);                                  // Set email format to HTML
$mail->Subject = utf8_decode($subject);
$mail->Body    = utf8_decode("<style>
body {background: linear-gradient(141deg, #ffffff 0%, #080708a1 51%,                           #000000 75%);}
.contenido
{
color: #428bca;
font-family: serif;
}
.msj1
{
color: #428bca;
}
.empresa
{
color: black;
}
</style>

<body>
<h3 class=msj1> Nombre: $user_name <br> </h3>
<h3 class=msj1> Fecha: $user_fecha <br> </h3>
<h3 class=msj1> Correo: $user_email <br> </h3>
<h3 class=msj1> Ocupacion: $user_ocupacion <br> </h3>
<h3 class=msj1> Domicilio: $user_domicilio <br> </h3>
<h3 class=msj1> Telefono: $user_telefono <br> </h3>
<h3 class=msj1> Nacionalidad: $user_nacionalidad <br> </h3>
<h3 class=msj1> Salario: $user_salario  <br> </h3>
<h3 class=msj1> Mensaje: $content <br> </h3>

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

Can anyone help me or point me on the right direction?

  • 4
    _What do you need to modify_ Your approach: Start by reading the `phpMailer` documentation. `phpMailer` makes it almost as easy as falling off a log. But you have to read the documentation to know that – RiggsFolly Dec 12 '18 at 16:26
  • thank you for your comments, sure i will read the documentation – Warkarian Ragnashark Dec 12 '18 at 16:39

2 Answers2

1

The file referenced for attachment needs to be located on the server and reachable with the full address of the file. When you upload the file, via Ajax, to attach -- where is it uploaded to?

Currently you have:

$mail->addAttachment('assets/pagina.zip'); 

A typical correct and fully qualified file reference would be:

$uploadFileName = 'assets/pagina.zip'; // or wherever you put Ajax uploads.
$mail->addAttachment($_SERVER['DOCUMENT_ROOT'].'/upload/'.$uploadFileName); 
// example string:   
// /home/accountname/public_html/upload/assets/pagina.zip
Martin
  • 22,212
  • 11
  • 70
  • 132
0

i was able to succesfully upload and send the mail with the attachment but now i cant add the rest of the form inputs. This is the way i changed the script to be able to attach the file, but this way i dont know how to post the rest of the information of the other inputs.

the html

$(document).ready(function (e){
    $("#contactForm").on('submit',(function(e){
      e.preventDefault();
      $('#boton').hide();
      $('#file').hide();
      var file_data = $('#file').prop('files')[0];   
      var form_data = new FormData();                  
      form_data.append('file', file_data);                            
      $.ajax({
        url: 'curriculum.php', // point to server-side PHP script 
        dataType: 'text',// what to expect back from the PHP script, if anything
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,                         
        type: 'post',               
        success: function(php_script_response){
          alert(php_script_response); // display response from the PHP script, if any
        }
      });
    }));
  });

on the php i added this code lines

 if ( 0 < $_FILES['file']['error'] ) {
    echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
    move_uploaded_file($_FILES['file']['tmp_name'], 'assets/' . $_FILES['file']['name']);
    $file='assets/' . $_FILES['file']['name'];
}

i tried combining the first script i had with this one but i havent figured out how to do it