Search code examples
javajakarta-mailimapuid

Using JavaMail how do I do a search and get a Message Array with UIDs I can reference?


So I am trying to figure out how to get messages with UIDs

IMAPStore store = (IMAPStore) session.getStore("imaps");
store.connect();
IMAPFolder folder = (IMAPFolder) store.getFolder(FOLDER_NAME);
folder.open(Folder.READ_ONLY);

Then I want to search the folder:

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

But the messages in the array are returned without UIDs, so how do I pull them out later for processing without an ID to reference them by?


Solution

  • I'm assuming you're talking about IMAP UIDs and you know how IMAP UIDs work. The deleted answer explained this well. Folder.search gives you a bunch of Message objects. Using the UIDFolder.getUID method, you can iterate over each of those Message objects and get its corresponding UID. Using the Folder.fetch method, you can prefetch those UIDs with a single IMAP command so the iteration over each Message to get its UID happens locally. If you save the UIDs, you can later use the UIDFolder methods to get back the corresponding Message objects. Don't forget to check the UIDVALIDITY.