Javamail search unread mails with a keyword (multiple searchterms)

1.8k Views Asked by At

I know how to search messages with keyword, I also know how to search unread messages. But I don't know how to combine those two things. Here is my code:

        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", "imaps");
        try {
            Session session = Session.getDefaultInstance(props, null);
            //GMail connecting
            Store store = session.getStore("imaps");
            store.connect("imap.gmail.com", user, password);
            Folder inbox = store.getFolder("Inbox");
            inbox.open(Folder.READ_WRITE);

            //Enter term to search here
            BodyTerm bodyTerm = new BodyTerm("abcd");
            FlagTerm flagTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);

            //can only search with one term at one time
            Message[] foundMessages = inbox.search(bodyTerm);
        }
        catch (MessagingException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
2

There are 2 best solutions below

0
On BEST ANSWER

Use AndTerm or OrTerm, depending on your needs.

You did read the javadocs, right?

0
On

You can use two or more searching criteria as shown below. I have given code for two search terms and can provide code for multiple search term using array

 Folder folderInbox = store.getFolder("INBOX");
            folderInbox.open(Folder.READ_WRITE);

            // fetches new messages from server with specific sender
            SearchTerm sender1 = new FromTerm(new InternetAddress("[email protected]"));

           //fetch only unread messages
            Flags seen = new Flags(Flags.Flag.SEEN);
            FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
            //searching sender
            //combire search tersm
            SearchTerm searchTerm = new AndTerm(unseenFlagTerm,sender1);

        Message[] arrayMessages = folderInbox.search(searchTerm);

In above code I have user specific shine.com as sender and only unread email as other search term.