2012-09-24 149 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

相關問題