【问题标题】:PHP Email Attachment pdf and docx files don't get sent properlyPHP 电子邮件附件 pdf 和 docx 文件未正确发送
【发布时间】:2013-12-03 22:38:56
【问题描述】:

好的,虽然我仍然知道更好的解决方案,但我正在使用手动 PHP 脚本来发送带有附件的电子邮件。我唯一的问题是某些附件(PDF、DOCX)在电子邮件中收到时是空白的。 我注意到,当我检查 $data 变量(存储文档文本的位置)时,在扩展名为 pdf 或 docx 的文件中,有额外的字符不是文件中消息的一部分。在 DOCX 文件中有一些额外的字符,在 PDF 中根本不显示内容,但会显示一些随机的废话(编码?)。不过理论上应该有一种方法可以附加 PDF 和 Docx 文件。 不知道如何解决这个问题。肯定会感谢一些帮助!我不想不得不求助于使用 PHPMailer 或 SwiftMailer。

这是我的代码:

$attachment = $_FILES['uploaded']['tmp_name'];
$att_type = $_FILES['uploaded']['type'];
$att_name = $_FILES['uploaded']['name'];

if (is_uploaded_file($attachment)) {
    // Read the file to be attached ('rb' = read binary)
    $file = fopen($attachment, 'rb');
    $data = fread($file, filesize($attachment));
    fclose($file);

    // Generate boundary string
    $semi_rand     = md5(time());
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

    // Add headers for file attachment
    $from .= "MIME-Version: 1.0\r\n";
    $from .= "Content-Type: multipart/mixed; boundary=\"{$mime_boundary}\"\r\n\r\n";

    // Message
    $message = "This is a multi-part message in MIME format.\r\n";
    $message .= "--{$mime_boundary}\r\n";
    $message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n\r\n";
    $message .= $msg . "\r\n\r\n";

    $data = chunk_split(base64_encode($data));

    // Attachment
    $message .= "\r\n--{$mime_boundary}\r\n";
    $message .= "Content-Type: {$att_type}; name=\"{$att_name}\"\r\n";
    $message .= "Content-Transfer-Encoding: base64\r\n";
    $message .= "Content-Disposition: attachment; filename=\"{$att_name}\"\r\n\r\n";
    $message .= $data . "\r\n";
    $message .= "--{$mime_boundary}--\r\n";
} else {
    $message = $msg;
}

// Send message
$success = mail($to, $subject, $message, $from);

有没有办法附加我丢失的 PDF 和 docx 文件?也许它与编码有关?或者也许我必须以不同的方式阅读文件(如果这是唯一的方法)。没有把握。有什么建议吗?

编辑:.pdf 文件在我添加编码后现在可以工作了。但是 .docx 文件仍然是空白的。所以关于 docx 的问题仍然存在!我用我所做的更改编辑了上面的代码。

编辑 2: .docx 文件有效!我用来测试的文件不正确,正常的 docx 文件可以正常运行!所以问题解决了。无需求助于 PHPMailer,尽管我确实尝试过并且效果很好。我现在要么切换到 PHPMailer,要么在需要向发送机制添加更多功能时使用它。否则,这个小脚本对于带有 1 个附件的简单电子邮件就足够了。

【问题讨论】:

  • 注意:对于随机值,只需使用uniqid()
  • 天哪,它刚刚成功了!!事实上,为了让 PDF 正确显示,我显然必须使用 64 编码。测试 docx.... 不!好吧,那一个仍然不起作用... 皱眉我明天会处理它。我将把它留在这里,因为这非常有帮助(我见过的对 mime 格式的最佳解释)-phpbuilder.com/columns/kartic20000807.php3?page=2
  • 我是用 PHPMailer 写的,但 docx 也有同样的问题,我怀疑我的 docx 文件不合法。现在要测试一下。

标签: php email pdf email-attachments docx


【解决方案1】:

使用这个,它更容易,并且经过测试:

http://www.phpclasses.org/package/32-PHP-A-class-for-sending-mime-email-.html

【讨论】:

    【解决方案2】:

    这两个文件现在都可以正常工作了。 PDF 文件必须具有编码(base64),并且在我补充说它们有效之后。 Docx 文件一直有效,但我最初使用错误的文件进行测试。那是造成问题的原因。所以问题解决了。没有必要求助于 PHPMailer,不过我也试过了,效果也很好。

    【讨论】:

      猜你喜欢
      • 2017-12-15
      • 1970-01-01
      • 2020-11-20
      • 2014-02-28
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 2021-11-21
      • 2013-02-07
      相关资源
      最近更新 更多