PHP电子邮件附件pdf和docx文件don';发送不正确


PHP Email Attachment pdf and docx files don't get sent properly

好的,虽然我仍然知道更好的解决方案,但我使用手动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个附件的简单电子邮件了。

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

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

这两个文件现在都可以正常工作。PDF文件必须有编码(base64),在我添加后,它们可以工作。Docx文件一直有效,但我最初使用了错误的文件进行测试。这就是问题的根源。所以问题解决了。没有必要求助于PHPMailer,但我也尝试过,效果也很好。