Counting the number of Emails in the Gmail INBOX

Suhail Gupta picture Suhail Gupta · Jul 24, 2011 · Viewed 9.3k times · Source

This is the code that counts the number of mails in the gmail inbox.

Properties props = new Properties();
    props.put("mail.pop3.host" , "pop.gmail.com");
    props.put("mail.pop3.user" , "username");
    props.put("mail.pop3.socketFactory" , 995 );
    props.put("mail.pop3.socketFactory.class" , "javax.net.ssl.SSLSocketFactory" );
    props.put("mail.pop3.port" , 995);
    Session session = Session.getDefaultInstance(props , new Authenticator() {
        @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication( "username" , "password");
                }
    });
    try {
        Store store  = session.getStore("pop3");
        store.connect("pop.gmail.com" , "username" , "password");
        Folder fldr = store.getFolder("INBOX");
        fldr.open(Folder.HOLDS_MESSAGES);
        int count = fldr.getMessageCount();
        System.out.println(count);
    } catch(Exception exc) {
        System.out.println(exc + " error");
    }

I get the count equal to 7 but i should get 3 because i have only 3 messages in the inbox.

Answer

Boris Treukhov picture Boris Treukhov · Jul 24, 2011

In GMAIL POP3 settings you should enable POP access only for the emails received from the current moment, it's standard GMAIL behavior.

When you enable POP, all messages are downloaded to your client, except for Spam, Trash, and Chats. If you don't want messages that you send from the web interface downloaded to your mail client's inbox, we suggest creating a filter within your client. You may want to contact your mail client's customer service department for instructions on how to categorize downloaded messages.

See the GMAIL troubleshooting article

AFAIK selective sync in GMAIL is only possible with IMAP protocol.