我使用的是我在这里找到的脚本: Downloading attachments to directory with IMAP in PHP, randomly works
连接到Gmail收件箱并下载某些附件。脚本是这样的:
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'XX@XX.com';
$password = 'XX';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to
Gmail: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox, 'FROM "xxx@gmail.com"');
/* if emails are returned, cycle through each... */
if($emails) {
/* begin output var */
$output = '';
/* put the newest emails on top */
rsort($emails);
foreach($emails as $email_number) {
/* get information specific to this email */
$overview = imap_fetch_overview($inbox,$email_number,0);
$message = imap_fetchbody($inbox,$email_number,2);
$structure = imap_fetchstructure($inbox,$email_number);
$attachments = array();
if(isset($structure->parts) && count($structure->parts)) {
for($i = 0; $i < count($structure->parts); $i++) {
$attachments[$i] = array(
'is_attachment' => false,
'filename' => '',
'name' => '',
'attachment' => '');
if($structure->parts[$i]->ifdparameters) {
foreach($structure->parts[$i]->dparameters as $object) {
if(strtolower($object->attribute) == 'filename') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['filename'] = $object->value;
}
}
}
if($structure->parts[$i]->ifparameters) {
foreach($structure->parts[$i]->parameters as $object) {
if(strtolower($object->attribute) == 'name') {
$attachments[$i]['is_attachment'] = true;
$attachments[$i]['name'] = $object->value;
}
}
}
if($attachments[$i]['is_attachment']) {
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i+1);
if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
}
elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
}
}
} // for($i = 0; $i < count($structure->parts); $i++)
} // if(isset($structure->parts) && count($structure->parts))
if(count($attachments)!=0){
foreach($attachments as $at){
if($at[is_attachment]==1){
file_put_contents($at[filename], $at[attachment]);
}
}
}
}
// echo $output;
}
/* close the connection */
imap_close($inbox);
它可以正常下载,但它似乎是破坏zip文件,起初我认为这是因为我试图访问的电子邮件每个都附加了两个zip文件,脚本可能会尝试将它们组合到一起一。但我通过发送一个仍然被破坏的文件进行测试。
我不完全理解脚本如何工作以了解如何修复它或导致问题的原因,所以任何人都可以帮忙吗?
编辑:
我刚刚通过发送不是ZIP的文件来测试它,它似乎破坏了所有文件类型或将它们保存为空,因为它们有0个文件大小。我还认为从Raspberry Pi运行脚本可能是一个问题,但我也在Debian Virtualbox机器上测试了它,结果相同。