php IMAP读取邮件信息

2024-11-20 17:24:17
推荐回答(1个)
回答(1):

$mbox = imap_open("{imap.gmail.com:993/imap/ssl}INBOX", "xxxx@gmail.com", "xxxx") or die("can't connect: " . imap_last_error());
$emails = imap_search($mbox,'ALL');
ini_set("max_execution_time",300);
if($emails) {
rsort($emails);
foreach($emails as $email_number) {
$overview = imap_fetch_overview($mbox,$email_number,0);
$pos = explode('@',$overview[0]->from);
$phone = substr($pos[0],-11); // 发件人手机号码
$struct = imap_fetchstructure($mbox, $email_number);
print_r($struct);
$parts = $struct->parts;
$i = 0;
if (!$parts) { /* Simple message, only 1 piece */
$attachment = array(); /* No attachments */
$content = imap_body($mbox, $email_number);
} else { /* Complicated message, multiple parts */
$endwhile = false; $stack = array(); /* Stack while parsing message */
$content = ""; /* Content of message */
$attachment = array(); /* Attachments */ while (!$endwhile) {
if (!$parts[$i]) {
if (count($stack) > 0) {
$parts = $stack[count($stack)-1]["p"];
$i = $stack[count($stack)-1]["i"] + 1;
array_pop($stack);
} else {
$endwhile = true;
}
}
if (!$endwhile) {
/* Create message part first (example '1.2.3') */
$partstring = "";
foreach ($stack as $s) {
$partstring .= ($s["i"]+1) . ".";
}
$partstring .= ($i+1);

$file_data = imap_fetchbody($mbox, $email_number, $partstring);
$attachment[] = array("filename" =>$parts[$i]->parameters[0]->value,
"filedata" => $file_data
);
if($parts[$i]->subtype == 'JPEG')
{
$file_name = md5(time().rand(5,200)).'.jpg';
file_put_contents($file_name,base64_decode($file_data));
}elseif($parts[$i]->subtype == 'GIF'){
$file_name = md5(time().rand(5,200)).'.gif';
file_put_contents($file_name,base64_decode($file_data));
}elseif($parts[$i]->subtype == 'PLAIN'){
$txt_name = time().rand(5,200).'.txt';
file_put_contents($txt_name,base64_decode($file_data));
}
}
if ($parts[$i]->parts) {
$stack[] = array("p" => $parts, "i" => $i);
$parts = $parts[$i]->parts;
$i = 0;
} else {
$i++;
}
} /* while */
} /* complicated message */
echo "userphone $phone, result:
";
echo "Content: $content

";
echo "Attachments:"; var_dump($attachment);
echo "

---------------------------------------------------------------------

";
}
}
imap_close($mbox);
?>