Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I quickly get a count of the messages in a user's mailbox?

Tags:

gmail-api

I'm attempting to get a count of ALL of the emails in a user's mailbox using the Gmail API. That means running something like

do{
    page = request.execute();
    if (page.getMessages() != null){
        totalSize += page.getMessages().size();
    }
    request.setPageToken(page.getNextPageToken());
}while (request.getPageToken() != null && request.getPageToken().length() > 0);

The issue is that for large mailboxes, this can be a long process, taking many API calls. For instance, one mailbox with 31,000 emails takes well over a minute to run, and takes 300+ iterations to do so.

Is there a better way?

I've tried using the maxResults parameter, but it defaults to 100 and ignores any values >100. Batch processing wouldn't work, because there's no way to know how many requests you have to make until you've iterated through every page already. And the resultSizeEstimate property in the List response is absurdly inaccurate.

like image 703
Dan Ambrogio Avatar asked Aug 29 '14 20:08

Dan Ambrogio


1 Answers

The Gmail API now provides total and unread counts for messages and threads on any Label using the Labels.Get() method. See: https://developers.google.com/gmail/api/release-notes and https://developers.google.com/gmail/api/v1/reference/users/labels

If you want to get message and thread counts for the entire mailbox (All mail) then use the new gmail.users.getProfile() method. You can try it out at the API explorer: https://developers.google.com/gmail/api/v1/reference/users/getProfile

like image 150
Eric D Avatar answered Sep 28 '22 01:09

Eric D