2009-09-17 180 views
1

我一直在努力嘗試使用PHP發送附件的電子郵件。它曾經工作,但消息正文被炒作。現在我得到了消息正文,但附件已損壞。我曾經使用base64編碼的消息正文,但現在使用7位。誰能告訴我我做錯了什麼?PHP郵件()附件損壞

PS請不要告訴我,我應該使用預製課程來做到這一點。我試了幾次,但都沒有成功。如果我沒有克服這些問題,我將永遠無法學會如何正確地做到這一點。由於

//define the receiver of the email 
$to = '[email protected]'; 
//define the subject of the email 
$subject = 'Your Disneyland Paris entry'; 
//create a boundary string. It must be unique 
//so we use the MD5 algorithm to generate a random hash 
$random_hash = md5(date('r', time())); 
//define the headers we want passed. Note that they are separated with \n 
$mime_boundary = "<<<--==+X[".md5(time())."]"; 

$path = $_SERVER['DOCUMENT_ROOT'].'/two/php/'; 
$fileContent = chunk_split(base64_encode(file_get_contents($path.'CTF_brochure.pdf'))); 


$headers .= "From: [email protected] <[email protected]>"."\n"; 

    $headers .= "MIME-Version: 1.0\n" . 
      "Content-Type: multipart/mixed;\n" . 
      " boundary=\"{$mime_boundary}\""; 

$message = "This is a multi-part message in MIME format.\n"; 

$message .= "\n"; 
$message .= "--".$mime_boundary."\n"; 

$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\n"; 
$message .= "Content-Transfer-Encoding: 7bit\n"; 
$message .= "\n"; 
$message .= "messagebody \n"; 
$message .= "--".$mime_boundary."" . "\n"; 

$message .= "Content-Type: application/octet-stream;\n"; 
$message .= " name=\"CTF-brochure.pdf\"" . "\n"; 
$message .= "Content-Transfer-Encoding: 7bit \n"; 
$message .= "Content-Disposition: attachment;\n"; 
$message .= " filename=\"CTF_brochure.pdf\"\n"; 
$message .= "\n"; 
$message .= $fileContent; 
$message .= "\n"; 
$message .= "--".$mime_boundary."--\n"; 

//send the email 
$mail_sent = mail($to, $subject, $message, $headers); 
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
echo $mail_sent ? "Mail sent" : "Mail failed"; 
+3

可以理解的是,你希望自己做這件事,但除了僅僅理解如何正確編碼郵件......你如果要學習一些東西,我會移動對我的項目有趣的部分,沒有重新發明輪... – Palantir 2009-09-17 12:41:44

+0

感謝您的意見。這是該項目唯一需要解決的問題。 :) – Drew 2009-09-17 13:08:52

回答

1

如果你想複雜的電子郵件,我建議你看phpmailer

7

我可能是錯的,但我相信你將不得不在某種程度上PDF編碼,7位不會爲PDF文件的工作將有範圍之外的內容。爲什麼不使用base64作爲PDF?

+0

謝謝。我剛剛放棄了,並沒有改變。 – Drew 2009-09-17 13:06:53

+0

你改變了哪些代碼?您是否嘗試使用base64編碼整個消息或只是附件?做出更改後,MIME標題的外觀如何? – Josh 2009-09-17 13:14:37

+0

我只是對附件做了修改。如果我base64整個消息,我得到奇怪的字符作爲消息正文 – Drew 2009-09-17 13:22:24

1

我知道你已經說過預構建的類,但有一個原因,人們這樣做 - 爲什麼重新發明輪子?我使用SwiftMailer進行項目 - 它不是那麼簡單。有關如何創建消息,添加附件併發送的13行(包括空白部分),請參閱this SwiftMailer example

至於你的實際查詢的決議,upvote喬希的答案 - 我會第二次改變編碼,看你如何繼續。您是否嘗試過獲取具有可用附件的示例電子郵件,並檢查原始數據?

+0

我確實爲此嘗試了swiftmailer,但它拒絕工作。它所設置的服務器非常刺耳 – Drew 2009-09-17 13:10:00