Search code examples
phpgmailimapgmail-imap

How to get Gmail unread count


I am using the following code to get the Unread emails count in Gmail. However, it is returning the error:

can't connect: Too many login failures

Is there anything I am missing here?

(IMAP and POP are enabled in the Gmail account I am testing.)


NOTE: It looks like it is working (at least for most of the requests). However, it is taking way too long - maybe 2 - 3 minutes to come back with a number. Is there a way to speed it up?


Thanks!

<?php

$mbox = imap_open ("{imap.gmail.com:993/imap/ssl/novalidate-cert/norsh}Inbox", 
"username", "password", OP_READONLY) 
or die("can't connect: " . imap_last_error()); 
$check = imap_mailboxmsginfo($mbox); 
if ($check) { 
print $check->Unread; //. "/" . $check->Nmsgs; 
} else { 
print "Failed"; 
}

?>

Solution

  • You can also use the Gmail Inbox Feed to get the unread count. Just send an authenticated GET request to https://mail.google.com/mail/feed/atom and check the value of the fullcount element.