【问题标题】:PHPMailer AddAttachmentPHPMailer 添加附件
【发布时间】:2019-10-10 23:20:55
【问题描述】:

我正在使用 PHPMailer 从表单发送数据,所有数据都已正确连接,并且适用于我的所有输入字段。除非我在以附件形式发送文件上传时遇到问题。

我的附加附件的 php 在下面

if(is_array($_FILES)) {
  $mail->AddAttachment($_FILES['image']['tmp_name'],$_FILES['image']['name']); 
}

这是输入文件的 HTML,以便您可以看到它的基本内容

<input type="file" id="image" name="image" class="" />

表单提交但在error_log中显示

PHP Notice:  Undefined index: image in /dir_location/mailer.php

哦,也只是为了排除,我正在使用&lt;form id="form" method="POST" enctype="multipart/form-data"&gt;

我也试过

if (array_key_exists('image', $_FILES)) {
      $uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['image']['name']));

      if (move_uploaded_file($_FILES['image']['tmp_name'], $uploadfile)) {
        $mail->addAttachment($uploadfile, 'UPLOAD file');
      }
}

但这也没有用。同样的问题。

非常感谢其他人的任何建议,谢谢。

【问题讨论】:

  • 是的,它返回完全相同的结果。
  • 如果您首先检查索引是否存在,则不会出现未定义的索引错误。 var_dump($_FILES); 显示什么?该错误消息是否链接到特定行,可能是您未在此处显示的代码?
  • var_dump 只显示array(0) {}
  • 这就解释了$_FILES['image'] 错误。如果您在浏览器中使用开发工具,它会在 POST 正文中显示正确的内容吗?如果是这样,您可能在 PHP 配置中禁用了文件上传。阅读the PHP docs on handling file uploads

标签: php phpmailer


【解决方案1】:

通过进一步研究,如果有人遇到 PHPMailer 和 Ajax 提交文件附件的问题,我找到了解决方案。

使用PHPMailer for file upload 提供的 PHP 文档,这适用于最终的 ajax 修正。

if (array_key_exists('userfile', $_FILES)) {

    $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name']));

    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
       // Attach the uploaded file
        $mail->addAttachment($uploadfile, $_FILES['userfile']['name']);
    //Send the message, check for errors
        if (!$mail->send()) {
            $msg = 'Sorry, something went wrong. Please try again later.';
        } else {
            $msg = 'Message sent! Thanks for contacting us.';
        }
    } else {
    }
}

Ajax提交表单,我需要更改formData并添加dataType。

$(function() {
  var form = $('#paymentForm');

    $(form).submit(function() {
      var formData = new FormData(this);

        $.ajax({
            type: 'POST',
            url: 'mailer.php',
            data: formData,
            dataType : "json",
            contentType: false,
            cache: false,
            processData: false
        })
    });

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-07
    • 2012-02-25
    • 2013-03-15
    • 2021-06-16
    • 1970-01-01
    • 2011-09-13
    • 1970-01-01
    相关资源
    最近更新 更多