2012-09-24 151 views
0

我已成功在网站上创建了PDF文件。我想要做的就是将该pdf作为附件发送到电子邮件中。到目前为止,似乎我已经成功连接的文件但试图打开附件Acrobat Reader软件给我这个错误消息时:PHP将电子邮件添加到电子邮件

Acrobat could not open 'example2.pdf' because it is either not a supported type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded) 

我觉得这个错误消息击中了要害,下面是我的代码有谁知道需要改变什么?感谢提前:)

$to = "[email protected]"; 
$from = "[email protected]"; 
$subject = "send email with pdf attachment"; 
$message = "<p>Please see the attachment.</p>"; 
// a random hash will be necessary to send mixed content 
$separator = md5(time()); 
// carriage return type (we use a PHP end of line constant) 
$eol = PHP_EOL; 
// attachment name 
$filename = "example.pdf"; 
// encode data (puts attachment in proper format) 
$attachment = chunk_split(base64_encode("/include/pdf.php?reportid=849980")); 
// main header (multipart mandatory) 
$headers = "From: ".$from.$eol; 
$headers .= "MIME-Version: 1.0".$eol; 
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"".$eol.$eol; 
$headers .= "Content-Transfer-Encoding: 7bit".$eol; 
$headers .= "This is a MIME encoded message.".$eol.$eol; 
// message 
$headers .= "--".$separator.$eol; 
$headers .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol; 
$headers .= "Content-Transfer-Encoding: 8bit".$eol.$eol; 
$headers .= $message.$eol.$eol; 
// attachment 
$headers .= "--".$separator.$eol; 
$headers .= "Content-Type: application/octet-stream; name=\"".$filename."\"".$eol; 
$headers .= "Content-Transfer-Encoding: base64".$eol; 
$headers .= "Content-Disposition: attachment".$eol.$eol; 
$headers .= $attachment.$eol.$eol; 
$headers .= "--".$separator."--"; 
// send message 
mail($to, $subject, "", $headers); 
+1

对于此MAX_INTth时间网站,不要建立你自己的哑剧电子邮件。使用[PHPMailer](http://phpmailer.worxware.com)或[Swiftmailer](http://swiftmailer.org)为你做。 –

+2

使用为您做附件处理的邮件库。没有必要自己写一切,两个常见的是Phpmailer和Swiftmailer。编辑:@MarcB:大声笑 – hakre

+1

他们说,与旋钮! – 2012-09-24 20:22:13

回答

0
$filename = "example.pdf"; 
// encode data (puts attachment in proper format) 
$attachment = chunk_split(base64_encode("/include/pdf.php?reportid=849980")); 

看起来是你的问题。您的附件似乎是PDF,而是一个PHP页面...也需要二进制(rb)读入pdf的文件内容,如下所示:

$filename = 'example.pdf'; 
$fileloc = '/path/to/pdf/'.$filename; 

$filehandle = fopen($fileloc, 'rb'); 
$data = fread($filehandle, filesize($fileloc)); 
fclose($filehandle);     

$attachment = chunk_split(base64_encode($data)); 
+0

感谢您的建议。我试过这个,但附件是空的。 – Paul

+0

好吧,做“var_dump($ data); exit;”在fclose()验证PDF已被正确读入$数据之后 – WebChemist

+0

这是你遵循的教程,对吧? http://www.daniweb.com/web-development/php/code/217105/generate-a-pdf-and-send-as-attachment – WebChemist

相关问题