2010-01-08 64 views
3

我試圖通過電子郵件將附件中的圖像發送到我的服務器上。爲了完成這個任務,我使用了下面的PHP腳本,它從我的服務器抓取一個名爲「截圖」的目錄中的JPG(稱爲「php.jpg」),並將其作爲附件發送。郵件中的電子郵件附件問題()

<?php 

$path = "screenshots/php.jpg"; 
$fp = fopen($path, 'r'); 
do //we loop until there is no data left 
{ 
     $data = fread($fp, 8192); 
     if (strlen($data) == 0) break; 
     $content .= $data; 
     } while (true); 
$content_encode = chunk_split(base64_encode($content)); 


$mime_boundary = "<<<--==+X[".md5(time())."]"; 

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

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

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

$message .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n"; 
$message .= "Content-Transfer-Encoding: 7bit\r\n"; 
$message .= "\r\n"; 
$message .= "Email content and what not: \r\n"; 
$message .= "This is the file you asked for! \r\n"; 
$message .= "--".$mime_boundary."\r\n"; 

$message .= "Content-Type: image/jpeg;\r\n"; 
$message .= " name=\"php.jpg\"\r\n"; 
$message .= "Content-Transfer-Encoding: quoted-printable\r\n"; 
$message .= "Content-Disposition: attachment;\r\n"; 
$message .= " filename=\"php.jpg\"\r\n"; 
$message .= "\r\n"; 
$message .= $content_encode; 
$message .= "\r\n"; 
$message .= "--".$mime_boundary."\r\n"; 

$ok = mail("[email protected]", "file by email", $message, $headers); 

總體而言,該腳本起作用。我在收件箱中收到一封電子郵件,其中包含上面指定的郵件文本和JPG附件。 Stack Overflow不會讓我張貼照片,因爲我是新手,但是屏幕截圖的信息可以在這裏找到:http://i48.tinypic.com/xfuee0.png

當我嘗試查看附件時,出現了我的問題。單擊附件只會打開一個新的瀏覽器窗口並顯示缺少的圖像圖標。

你是否看到我的腳本有任何問題會阻止圖像出現?

任何信息都會很棒。謝謝!

+0

我試圖從wallyk和martinr到目前爲止(感謝你們!),但沒有運氣的建議。我想知道郵件功能是否正常,只是我的fopen循環沒有產生正確的圖像。 任何人可以提供任何其他建議,將不勝感激。感謝大家! – Matt 2010-01-08 02:16:10

回答

0

我可以看到一個可能的原因,爲什麼你看不到你的形象。 (可能還有更多(!)。)

嘗試改變:

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

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

對於調用郵件之前的最後一行(即 「尾聲」 邊界)。

0

三件事跳出:

之一是,第一個添加變量$content$message$headers沒有明確設置一個新值。也就是說,爲什麼不

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

,而不是像你這樣:

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

這消除了一些吃剩的東西被掛在變量的可能性。

第二個是有\r\n而不是\n,它應該適用於每個系統,甚至是Windows。我懷疑這是一個問題。

三是封閉式模擬邊界與開放不一樣。

+1

根據RFC 822,\ r \ n是結束標題字段的正確方法。 – 2010-01-08 02:24:58

3

對於任何未來遇到此帖子的人來說,問題來自應該設置爲base64的「Content-Transfer-Encoding」。

$message .= "Content-Transfer-Encoding: quoted-printable\r\n"; 

變爲:

$message .= "Content-Transfer-Encoding: base64\r\n";