Javamail 使用关键字搜索未读邮件(多个搜索词)

Javamail search unread mails with a keyword (multiple searchterms)

我知道怎么用关键字搜索消息,我也知道怎么搜索未读消息。但我不知道如何将这两件事结合起来。 这是我的代码:

        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();
        }

根据需要使用AndTerm or OrTerm

您确实阅读了 javadocs,对吧?

您可以使用两个或多个搜索条件,如下所示。我已经给出了两个搜索词的代码,并且可以使用 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("alert@shine.com"));

           //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);

在上面的代码中,我将特定于用户的 shine.com 作为发件人,并将未读电子邮件作为其他搜索词。