Search code examples
javaemailgmailjakarta-mail

How to read e-mails from inbox of a GMail account in Java?


I need to read e-mails from a Gmail account. I wrote the following code:

public class ReadResponseToEmailTest {
    @Test
    public void testGmailConnection() throws MessagingException {
        Folder emailFolder = null;
        Store store = null;
        try {
            //create properties field
            Properties properties = new Properties();

            properties.put("mail.pop3.host", "pop.gmail.com");
            properties.put("mail.pop3.port", Integer.toString(995));
            properties.put("mail.pop3.starttls.enable", "true");

            Session emailSession = Session.getDefaultInstance(properties);

            //create the POP3 store object and connect with the pop server

            store = emailSession.getStore("pop3s");

            store.connect("pop.gmail.com", "[email protected]", "XXXXXXXX");

            //create the folder object and open it

            emailFolder = store.getFolder("INBOX");
            emailFolder.open(Folder.READ_ONLY);

            // retrieve the messages from the folder in an array and print it
            Message foundMessage = null;
            Message[] messages = emailFolder.getMessages();
            for (final Message msg : messages) {
                final String subject = msg.getSubject();
            }
        }
        finally {
            if (emailFolder != null) {
                emailFolder.close(false);
            }
            if (store != null) {
                store.close();
            }
        }

    }
}

messages contains only old messages. Also, most of these messages are not located in the inbox, but are archived.

How do I need to change the above code in order to be able to read e-mails from GMail's inbox (especially the recently received ones)?


Solution

  • Check your gmail account settings:

    • In the top right, click Settings ⚙ ⇒ See all settings.

    • Click on the Forwarding and POP/IMAP tab.

    • Enable POP for all mail (even mail that's already been downloaded)

    enter image description here

    • Also try to check second radio-button: Enable POP for mail that arrives from now on to not to receive archived messages.

    See: Read Gmail messages on other email clients using POP - Gmail Help