如何在PHP中将邮件附件保存到服务器? [英] How can I save email attachments to the server in PHP?
问题描述
在两天之内,我一直在和PHP的电子邮件阅读功能进行比较。我正在编写一个脚本来从邮箱读取邮件,并将任何附件保存到服务器上。如果你曾经做过类似的事情,你可能会明白我的痛苦: PHP不能很好地发送邮件!
I've been battling PHP's email reading functions for the better part of two days. I'm writing a script to read emails from a mailbox and save any attachments onto the server. If you've ever done something similar, you might understand my pain: PHP doesn't play well with email!
我已经连接到POP3服务器,我可以迭代文件。以下是代码的粗略概述:
I've connected to the POP3 server and I can iterate the files. Here's a rough outline of the code:
if (!$mbox = imap_open ("{myserver.com:110/pop3/notls}INBOX", "u", "p"))
die ('Cannot connect/check mail! Exiting');
if ($hdr = imap_check($mbox))
$msgCount = $hdr->Nmsgs;
else
die ("Failed to get mail");
foreach ($overview as $message) {
$msgStruct = imap_fetchstructure($mbox, $message->msgno);
// if it has parts, there are attachments that need reading
if ($msgStruct->parts) {
foreach ($msgStruct->parts as $key => $part) {
switch (strtoupper($part->subtype)) {
case 'GIF': case 'JPEG':case 'PNG':
//do something - but what?!
break;
}
}
}
}
'我标记在我被卡住的地方。我可以使用 imap_fetchbody($ mbox,$ message-> msgno,$ key + 1)
,但是这可以让我得到如下一些数据:
I've marked where I'm stuck. I can use imap_fetchbody($mbox, $message->msgno, $key+1)
but that gets me a bunch of data like this:
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8S
EhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEU
Hh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAAR
CAHiAi0DASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAA
AgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkK
FhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWG
h4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl
5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREA
...
我相信这是MIME数据。我需要它作为一个图像!我已经看到几个类在网络上轰炸声称要做所需的魔法。我不能让任何人上班。我不明白为什么我发现这么难!
I'm lead to believe that this is MIME data. I need it as an image! I've seen several classes bombing around the internet that claim to do the required wizardry. I can't get any of them to work. I don't understand why I'm finding this so hard!
简而言之,我正在寻找一些可以变成原始MIME字符串转换成实际数据。
In short, I'm looking for something that can turn a raw MIME string into real data.
推荐答案
我发现一个快速指南如何使用PHP处理电子邮件:这里。
I found a quick guide how to treat emails with PHP: here.
在该页面的底部有一个附件体 echo
:
At the bottom of that page there's a attachment-body echo
:
if (substr($ContentType,0,4) == "text") {
echo imap_qprint($fileContent);
} else {
echo imap_base64($fileContent);
}
我想这是你可能需要的...
I guess this is what you might need...
(编辑:在你的情况下,如果它的图像总是你可以跳过如果
部分,当然,保存文件而不是回显它:)
(edit: in your case if it's image always you can skip the if
part. And of course, save the file instead of echoing it:)
这篇关于如何在PHP中将邮件附件保存到服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!