在我目前的项目中,我必须动态创建一个PDF文件并作为邮件附件附加并发送。它工作正常,文件生成并发送到我提供的电子邮件。当我将其发送到Microsoft Outlook或Windows Live帐户时,PDF已附加但无法使用pdf打开文件,并给出错误说明,其已损坏。但是使用gmail和雅虎它可以正常工作。有没有人有这方面的解决方案。以下是我的代码
$dompdf = new DOMPDF();
$dompdf->load_html($message);
$dompdf->set_paper("a4", "landscape");
$dompdf->render();
// The next call will store the entire PDF as a string in $pdf
$pdf = $dompdf->output();
// You can now write $pdf to disk, store it in a database or stream it to the client.
file_put_contents("pdfs/invoice.pdf", $pdf);
$fileatt = "pdfs/invoice.pdf"; // Path to the file
$fileatt_type = "pdf"; // File Type
$fileatt_name = "invoice.pdf"; // Filename that will be used for the file as the attachment
$fp = fopen($fileatt, "rb");
$file = fread($fp, filesize($fileatt));
$file = chunk_split(base64_encode($file));
$num = md5(time());
$to = "mail@mail.com";
$subject = "Invoice";
$headers = "From: " . "Manager" . "<" . "mail@mail.com" . ">\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; ";
$headers .= "boundary=".$num."\r\n";
$headers .= "--$num\r\n";
$headers .= "Message-ID: <" . gettimeofday() . " TheSystem@" . $_SERVER['SERVER_NAME'] . ">\r\n";
$headers .= "X-Mailer: PHP v" . phpversion() . "\r\n";
$headers .= "Content-Type:".$fileatt_type." ";
$headers .= "name=\"".$fileatt_name."\"r\n";
$headers .= "Content-Transfer-Encoding: base64\r\n";
$headers .= "Content-Disposition: attachment; ";
$headers .= "filename=\"".$fileatt_name."\"\r\n";
$headers .= "".$file."\r\n";
$headers .= "--".$num."\r\n";
$headers .= "Content-Type: text/html; charset=iso-8859-1\r\n";
$headers .= "".$message."\r\n";
$headers .= "--".$num."--";
if (mail($to, $subject, $message, $headers)) {
fclose($fp);
echo "Success";
//header("location: client.php?m=1");
} else {
echo "Error";
//header("location: client.php?m=0");
}
希望有人能帮助我解决问题。
答案 0 :(得分:2)
构建自己的mime消息绝不是一个好主意。请改用PHPMailer或Swiftmailer。它们都处理构建消息的繁重工作,包括文件附件。最重要的是,它们都是免费的,并且远远优于内置的PHP邮件功能。上面的代码可以减少到6行邮件发送代码中的大约5行。
答案 1 :(得分:1)
我已经挣扎了近一天,发现Outlook似乎没有识别附件,除非边界以制表符(\t
)作为前缀。
例如:
$headers.="Content-type: multipart/mixed;\r\n\tboundary=\"uniqueID\"\r\n\r\n";
您还需要同时使用\r\n
和
确保每个边界(及其说明)与内容之间有明确的界限。