请帮忙。我意识到这是基本的东西,但我很困惑为什么我的PDF是空的。我收到带有PDF附件的电子邮件,但它们是空的PDF文件,我无法弄清楚原因。我在这里看了其他类似的问题,但没有发现它们有用。我不希望使用框架或依赖项。谢谢您的帮助。我希望在15分钟内完成这项工作,但这个错误让我反感。
$dir = "scanned_files";
function is_dir_empty($dir) {
if(!is_readable($dir)){
return NULL;
}
$handle = opendir($dir);
while(false !== ($entry = readdir($handle))){
if ($entry != "." && $entry != "..") {
return FALSE;
}
}
return TRUE;
}
if (is_dir_empty($dir)) {
echo "the folder is empty";
}else{
$files = array_diff(scandir($dir), array('.', '..', '.DS_Store'));
foreach($files as $filename){
$content = file_get_contents($dir . "/" . $filename);
$content = chunk_split(base64_encode($content));
$email = "someone@somewhere.com";
$subject = "Scanned document from the road!";
$separator = md5(time());
$headers = "From: someone@somewhere.com" . "\r\n";
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: multipart/mixed; boundary=\"" . $separator . "\"" . "\r\n";
$headers .= "Content-Transfer-Encoding: 7bit" . "\r\n";
$msg = "--" . $separator . "\r\n";
$msg .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . "\r\n";
$msg .= "Content-Transfer-Encoding: 8bit" . "\r\n";
$msg .= "Your file has arrived." . "\r\n";
$msg .= "--" . $separator . "\r\n";
$msg .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"" . "\r\n";
$msg .= "Content-Transfer-Encoding: base64" . "\r\n";
$msg .= "Content-Disposition: attachment" . "\r\n";
$msg .= $content . "\r\n";
$msg .= "--" . $separator . "--";
mail($email, $subject, $msg, $headers);
echo PHP_EOL . "Mail sent. Filename: " . $filename . PHP_EOL;
}
}
答案 0 :(得分:0)
使用multi-part/mixed
内容类型时,每个部分必须有一个空白行,将标题与正文分开。
每个部分以封装边界开头,然后包含一个 正文部分由标题区域,空行和正文区域组成。
在您的代码中,生成的标题和消息之间没有任何空行。
要解决此问题,请在以下行中使用\r\n\r\n
代替\r\n
:
$headers .= "Content-Transfer-Encoding: 7bit" . "\r\n\r\n";
$msg .= "Content-Disposition: attachment" . "\r\n\r\n";
然后你的附件就会正确出来。