我知道如何使用关键字搜索邮件,我也知道如何搜索未读邮件。但我不知道如何将这两件事结合起来。这是我的代码:
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或OrTerm。
你确实读过javadocs,对吧?
您可以使用两个或多个搜索条件,如下所示。我已经给出了两个搜索词的代码,并且可以使用数组为多个搜索词提供代码
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 作为发件人,并且仅将未读电子邮件作为其他搜索词。