我需要修改什么才能使用phpmailer表单发送附件?

时间:2018-12-12 16:22:30

标签: php html phpmailer attachment

我在我的网站上有一个工作正常的phpmailer联系人表格,现在我希望能够将文件附加到邮件中并能够发送,但是我不知道如何发布数据。

这是我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);
              } 
          });
      }));
  });

使用此脚本,我可以输入下一个php,并且现在已经发送了我的电子邮件,我已经手动设置了邮件的附件,但显然我想删除该行并能够从网站上载ht文件

<?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;
}
?>

任何人都可以帮助我或为我指明正确的方向吗?

2 个答案:

答案 0 :(得分:1)

引用的附件文件必须位于服务器上,并且可以使用文件的完整地址访问。当您通过Ajax上传文件时,该文件将附加到何处?

当前您拥有:

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

典型的正确且完全合格的文件引用为:

$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

答案 1 :(得分:0)

我能够成功上传并发送带有附件的邮件,但是现在我无法添加其余的表单输入。这是我更改脚本以能够附加文件的方式,但是我不知道如何发布其他输入的其余信息。

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
        }
      });
    }));
  });

在php上,我添加了以下代码行

 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'];
}

我尝试将我拥有的第一个脚本与此脚本结合在一起,但是我还没有弄清楚该怎么做