2010-01-08 82 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";