我想拒绝。来自 gmail 帐户的最近未读邮件。为此,我在我的 Ubuntu 系统中安装了 IMAP,并尝试了一些 PHP iMAP 功能。 以下是我到目前为止所做的尝试。
/* connect to gmail */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'user@gmail.com';
$password = 'user_password';
/* try to connect */
$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
现在我正在陈述我所有的尝试。 注意 - 我已通过向测试电子邮件 ID 发送新邮件来尝试每次尝试
尝试_1:使用 imap_search()
$recent_emails = imap_search($inbox,'RECENT');
if ($recent_emails)
echo count($recent_emails);
else
echo "false return";
imap_close($inbox);
现在 Attempt_1 的输出是“false return”;
尝试_2:使用 imap_mailboxmsginfo()
$check = imap_mailboxmsginfo($inbox);
if ($check)
echo "Recent: " . $check->Recent . "<br />\n" ;
else
echo "imap_check() failed: " . imap_last_error() . "<br />\n";
imap_close($inbox);
这里的输出是 Recent:0 而我已经向这个 id 发送了 2 封新邮件
尝试_3:使用 imap_status()
$status = imap_status($inbox, $hostname, SA_ALL);
if ($status)
echo "Recent: " . $status->recent . "<br />\n";
else
echo "imap_status failed: " . imap_last_error() . "\n";
//最近输出:0
尝试 4:再次使用带有参数 NEW 的 Using imap_search()
$recent_emails = imap_search($inbox,'NEW');
if ($recent_emails)
echo count($recent_emails);
else
echo "false return";
imap_close($inbox);
输出-返回错误
那么我哪里错了? 如何获取最近的未读邮件数?
最佳答案
这个函数似乎有效:
function CountUnreadMail($host, $login, $passwd) {
$mbox = imap_open($host, $login, $passwd);
$count = 0;
if (!$mbox) {
echo "Error";
} else {
$headers = imap_headers($mbox);
foreach ($headers as $mail) {
$flags = substr($mail, 0, 4);
$isunr = (strpos($flags, "U") !== false);
if ($isunr)
$count++;
}
}
imap_close($mbox);
return $count;
}
用法:
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'user@gmail.com';
$password = 'user_password';
$count = CountUnreadMail($hostname, $username, $password);
我不能完全归功于此功能。这是 sdolgy 对 PHP Displaying unread mail count 的回答的略微编辑版本.他的版本采用 POP 邮件。此版本需要完整的 $hostname
。我用我自己的 Gmail 帐户对其进行了测试,它正确地报告了我收件箱中的未读 邮件数。
PHP Displaying unread mail count有一些很好的阅读 Material 。检查一下。
希望这对您有所帮助。
更新
发件人:Does Gmail support all IMAP features?
Gmail IMAP1 is a fairly complete implementation of IMAP, but the following features are currently unsupported:
\Recent flags on messages.
验证于:Gmail's Buggy IMAP Implementation
Gmail doesn't handle standard IMAP flags, such as "\Deleted", "\Answered", and "\Recent".
另请参阅: Jyoti Ranjan's answer (下)寻找可能的解决方案。
关于php - PHP中使用IMAP()获取近期未读邮件数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7363077/