我的Gmail中有2465封电子邮件,为什么程序在下载完所有电子邮件后都无法停止?所有code1和code2都以命令行模式运行 code1:
<?php
$mailbox = array(
'mailbox' => '{imap.gmail.com:993/imap/ssl}INBOX',
'username' => 'xxxx@gmail.com',
'password' => 'yyyy'
);
$stream = imap_open($mailbox['mailbox'], $mailbox['username'], $mailbox['password'])
or die('Cannot connect to mailbox: ' . imap_last_error());
$emails = imap_search($stream,"ALL");
$nums=imap_num_msg($stream);
echo $nums;
foreach($emails as $email_id) {
$mime = imap_fetchbody($stream, $email_id, "");
file_put_contents("/tmp/" . "email_{$email_id}.eml", $mime);
}
imap_close($stream);
echo "over";
?>
代码1:
1.可以下载所有的电子邮件
2.控制台上的输出2465
3.控制台上没有over
输出
程序无法停止,它似乎永远运行。
code2:
<?php
$mailbox = array(
'mailbox' => '{imap.gmail.com:993/imap/ssl}INBOX',
'username' => 'xxxx@gmail.com',
'password' => 'yyyy'
);
$stream = imap_open($mailbox['mailbox'], $mailbox['username'], $mailbox['password'])
or die('Cannot connect to mailbox: ' . imap_last_error());
$emails = imap_search($stream,"ALL");
$nums=imap_num_msg($stream);
echo $nums;
foreach($emails as $email_id) {
echo $email_id.PHP_EOL;
$mime = imap_fetchbody($stream, $email_id, "");
file_put_contents("/tmp/" . "email_{$email_id}.eml", $mime);
}
imap_close($stream);
echo "over";
?>
代码2:
1.可以下载所有的电子邮件
2.控制台上的输出2465
3。控制台上的over
输出
4.下载完所有电子邮件后程序停止。
code2中有一行echo $email_id.PHP_EOL;
比code1多,其他代码相同
所有code1和code2都以命令行模式运行
谁可以解释一下?
答案 0 :(得分:1)
尝试
print imap_last_error();
在imap_close
之前和之后了解更多有关导致问题的原因
答案 1 :(得分:0)
检查imap_fetchbody()
功能,此功能允许您设置下载限制,并且可以在所有邮件下载后停止。检查下面的代码,我对您的代码进行了一些更改,这些更改将在所有邮件下载后停止下载过程。请检查一次。
<?php
$mailbox = array(
'mailbox' => '{imap.gmail.com:993/imap/ssl}INBOX',
'username' => 'xxxx@gmail.com',
'password' => 'yyyy'
);
$stream = imap_open($mailbox['mailbox'], $mailbox['username'], $mailbox['password'])
or die('Cannot connect to mailbox: ' . imap_last_error());
//Check all mails...
$imap_obj = imap_check($stream);
// Fetch an overview for all messages in INBOX...
$nums=imap_num_msg($stream);
$emails = imap_fetch_overview($stream,"1:{$imap_obj->Nmsgs}",0);
echo $nums;
//Loop until mail data...
foreach($emails as $objEmail_data) {
$mime = imap_fetchbody($stream, $objEmail_data->msgno, "");
file_put_contents("/tmp/" . "email_{$objEmail_data->msgno}.eml", $mime);
}
imap_close($stream);
echo "over";
?>
看到结果!
我将imap_search()
替换为imap_fetch_overview()
并进行了一些相关更改。
如果需要进一步的帮助,请告诉我。
答案 2 :(得分:-1)
<?php
$mailbox = array(
'mailbox' => '{imap.gmail.com:993/imap/ssl}INBOX',
'username' => 'xxxx@gmail.com',
'password' => 'yyyy'
);
$stream = imap_open($mailbox['mailbox'], $mailbox['username'], $mailbox['password'])
or die('Cannot connect to mailbox: ' . imap_last_error());
$emails = imap_search($stream,"ALL");
$nums=imap_num_msg($stream);
//echo $nums; // removed this
foreach($emails as $email_id) {
$mime = imap_fetchbody($stream, $email_id, "");
file_put_contents("/tmp/" . "email_{$email_id}.eml", $mime);
}
unset($emails); // added this
imap_close($stream);
die ("over"); // changed this
?>
我已重置电子邮件变量。