我非常接近完成此操作,但我仍然坚持下载附件。
到目前为止,我正在使用以下代码抓取所有必要的电子邮件标题信息:
(另外,我是通过命令行执行此操作:CentOS 6)
<?php
echo "\n";
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'myemail@mydomain.com';
$password = 'myfunpassword';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
/* grab emails */
$emails = imap_search($inbox,'ALL');
/* if emails are returned, cycle through each... */
if($emails) {
/* begin output var */
$output = '';
/* put the newest emails on top */
rsort($emails);
/* for every email... */
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,1);
$output.= $email_number."\n";
$output.= ($overview[0]->seen ? '[read]' : '[unread]')."\n";
$output.= "date:".$overview[0]->date."\n";
$output.= "to:".$overview[0]->to."\n";
$output.= "from:".$overview[0]->from."\n";
$output.= "size:".$overview[0]->size."\n"; //size in bytes
$output.= "msgno:".$overview[0]->msgno."\n";
$output.= "message_id:".$overview[0]->message_id."\n"; //Message-ID
$output.= "uid:".$overview[0]->uid."\n"; //UID the message has in the mailbox
$output.= "from:".$overview[0]->from."\n";
$output.= "subject:".$overview[0]->subject."\n";
/* output the email body */
$output.= "message:".$message;
/* detect attachments here */
$output.="\n\n";
}
echo $output;
} // eof $emails check
imap_close($inbox);
?>
这很棒! 所以现在,我已经有了这段代码告诉我每封电子邮件中是否有附件:
<?php
// put this code above where it says "detect attachments here"
// attachments detection
$struct = imap_fetchstructure($inbox,$email_number);
$contentParts = count($struct->parts);
if ($contentParts >= 2) {
for ($i=2;$i<=$contentParts;$i++) {
$att[$i-2] = imap_bodystruct($inbox,$email_number,$i);
}
for ($k=0;$k<sizeof($att);$k++) {
if ($att[$k]->parameters[0]->value == "us-ascii" || $att[$k]->parameters[0]->value == "US-ASCII") {
if ($att[$k]->parameters[1]->value != "") {
$selectBoxDisplay[$k] = $att[$k]->parameters[1]->value;
}
} elseif ($att[$k]->parameters[0]->value != "iso-8859-1" && $att[$k]->parameters[0]->value != "ISO-8859-1") {
$selectBoxDisplay[$k] = $att[$k]->parameters[0]->value;
}
}
if (sizeof($selectBoxDisplay) > 0) {
for ($j=0;$j<sizeof($selectBoxDisplay);$j++) {
$output.= "\n--file:". $selectBoxDisplay[$j]."";
}
}
}
// eof attachments detection
?>
这也有效!但现在我需要下载附件,大多数教程向我展示了如何使用浏览器的角度而不是CLI。所以我在这里肯定需要一些帮助。
我期待有办法确定在服务器上下载文件的位置。