带有附件的PHP邮件-但文件为空

时间:2018-12-10 15:29:49

标签: php

制作一个PHP脚本,该脚本还包含一个文本文件作为附件。当我发送到GMAIL地址时,它可以正常工作,但是当我发送到另一个Web主机上的地址时,我可以看到该文件已附加,但是当我打开它时,该文件为空(无内容)。是什么原因造成的?这是我使用的代码:

$filename = basename($dirfilename);
$body = "File is included in mail";

$path = "downloads/";

$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);

$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);

$eol = PHP_EOL;

// Headers
$header = "From: ".$from_name." <".$from_mail.">".$eol;
$header .= "Reply-To: ".$replyto.$eol;
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"";

// Message
$message = "--".$uid.$eol;
$message .= "Content-Type: text/html; charset=UTF-8".$eol;
$message .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
$message .= $body.$eol;
$message .= "--".$uid.$eol;
$message .= "Content-Type: text/plain; name=\"".$filename."\"".$eol;
$message .= "Content-Transfer-Encoding: base64".$eol;
$message .= "Content-Disposition: attachment;\r\n filename*=utf-8''" . rawurlencode($filename).$eol;
$message .= $content.$eol;
$message .= "--".$uid."--";

if (mail($mail_to, $subject, $message, $header))
{
    echo "File sent";
} else {
    echo "Fail";
}

1 个答案:

答案 0 :(得分:1)

如果您查看原始电子邮件:

--_004_8b72e1a6b3f242208a89b3fa9240bcf3avode_
Content-Type: application/pdf; name="TA1_031_21204-2.pdf"
Content-Description: TA1_031_20181204-2.pdf
Content-Disposition: attachment; filename="TA1_031_21204-2.pdf";
    size=230847; creation-date="Mon, 10 Dec 2018 11:33:32 GMT";
    modification-date="Mon, 10 Dec 2018 09:44:35 GMT"
Content-Transfer-Encoding: base64

JVBERi0xLjUNJeLjz9MNCjI4MDYgMCBvYmoNPDwvTGluZWFyaXplZCAxL0wgMjMwODQ3L08gMjgw
OC9FIDMzOTcvTiAyOC9UIDIzMDE2NS9IIFsgNDY3IDM0NF0+Pg1lbmRvYmoNICAgICAgICAgICAg
DQoyODEyIDAgb2JqDTw8L0RlY29kZVBhcm1zPDwvQ29sdW1ucyA0L1ByZWRpY3RvciAxMj4+L0Zp
bHRlci9GbGF0ZURlY29kZS9JRFs8MDU4QTRCNjk5OEFDNzE0M0JCRUZEMDFENjJCOEE5ODg+PDZG
Q0FDM0U1RTAyOTNDNDU5QzE2MkQzMTczMjM5RTYyPl0vSW5kZXhbMjgwNiAxM10vSW5mbyAyODA1

通过编写电子邮件的方式

$message .= "Content-Disposition: attachment;\r\n filename*=utf-8''" . rawurlencode($filename).$eol;

您要在文件内容前添加一个不必要的'\ r \ n'并且没有$ eol。

尝试类似的东西:

$message .= 'Content-Disposition: attachment; filename=". rawurlencode($filename).";'.$eol.$eol;

但这将由PHPMailer自动完成。