Search code examples
javajakarta-mailimapgmail-imap

Get only unseen mails from Gmail - imap


I have this code:

Properties properties = new Properties();
properties.setProperty("mail.store.protocol", "imaps");
    
try(Store store = Session.getDefaultInstance(properties, null).getStore("imaps")){

    store.connect("imap.gmail.com", 993, username, password);

    Folder inboxFolder = store.getFolder("INBOX");
    
    try(inboxFolder){
    
        //open folder
        inboxFolder.open(Folder.READ_WRITE);
        
        //get messages
        Message[] messages = inboxFolder.search(new FlagTerm(new Flags(Flags.Flag.RECENT), true));
        
        Arrays.stream(messages)
            .forEach(message -> {
            
                try{
                
                    System.out.println(message.getSubject());
                    
                }catch(Exception e){ e.printStackTrace(); }
                
            };  
                
    }

}catch(Exception e){
    e.printStackTrace();
}

I try to read all unseen mails from INBOX from GMail.

But in console is printed nothing and messages.length is 0.

How I can read just unseen mails?

P.S.: I just printed the flag of all messages(doesn't matter the flag) and I realized the unseen messages has no flag. This is how it is supposed to be?

P.S.: I found out.

Message[] messages = inboxFolder.search(
    new FlagTerm(new Flags(Flags.Flag.SEEN), false)
);

With this one works: new FlagTerm(new Flags(Flags.Flag.SEEN), false)


Solution

  • I found the solution.

    Instead of

    new FlagTerm(new Flags(Flags.Flag.RECENT), true)
    

    I need to do this

    new FlagTerm(new Flags(Flags.Flag.SEEN), false)
    

    To get the unseen messages.