How to get Gmail unread count

2019-04-11 23:13发布

问题:

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"; 
}

?>

回答1:

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.



回答2:

Try outputting all of the errors that may have been encountered:

$mbox = imap_open("{imap.gmail.com:993/imap/ssl/novalidate-cert/norsh}Inbox", "username", "password", OP_READONLY) or die('Cannot connect to Gmail: ' . print_r(imap_errors()));


回答3:

I have same problem and it is very simple.

Login with your account which is you use for imap connection and at the top of page google alter you about the multi location access your account so Goolge privent that so complete that process and enable to use your accout

and your problem will resolved.



回答4:

The easiest way is to make a authenticated GET request to gmail api. url :: https://www.googleapis.com/gmail/v1/users/me/labels/UNREAD

It will return a json with count of unread messages n threads. countUnread = response["messagesTotal"]. For more details, refer to oauth 2 playground. https://developers.google.com/oauthplayground/?code=4/-49VJwh28-eJG7xiK3UoFBchIQrCYRllnOt1TY-w0h4#