I am trying to get no. of recent unread mails from a gmail account.For this I have installed IMAP in my Ubuntu system and tried some PHP iMAP functions.Here are what i have tried till now./* connect to gmail */$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';$username = '[email protected]';$password = 'user_password';/* try to connect */$inbox = imap_open($hostname,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());Now I am stating all my attempts.NB - I have tried each attempt by sending new mails to the testing email idAttempt_1: Using imap_search()$recent_emails = imap_search($inbox,'RECENT');if ($recent_emails) echo count($recent_emails);else echo "false return";imap_close($inbox);Now Output of Attempt_1 is "false return";Attempt_2: Using 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);Here the output is Recent:0 while I have sent 2 new mails to this idAttempt_3: using 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";//Output Recent:0Attempt_4: Using Using imap_search() Again with parameter NEW$recent_emails = imap_search($inbox,'NEW');if ($recent_emails) echo count($recent_emails);else echo "false return";imap_close($inbox);Output - false returnSo Where Am I WRONG?How can I get the recent unread emails count? 解决方案 This function seems to work: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;}Usage:$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';$username = '[email protected]';$password = 'user_password';$count = CountUnreadMail($hostname, $username, $password);I can’t claim full credit for this function. It’s a slightly edited version of sdolgy’s answer to PHP Displaying unread mail count. His version assumed POP mail. This version requires the full $hostname. I tested it with my own gmail account and it correctly reported the number of unread messages I had in my inbox.PHP Displaying unread mail count has some pretty good reading material. Check it out.Hope this helps.UPDATEFrom: Does Gmail support all IMAP features?Verfied at: Gmail's Buggy IMAP ImplementationSee also: Jyoti Ranjan's answer (below) for a possible solution. 这篇关于在PHP中使用IMAP()获取最近的未读电子邮件计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 1403页,肝出来的..
09-07 23:34