Search code examples
javaimapfetchjakarta-mail

How can I combine multiple IMAP fetch commands?


I'm using JavaMail to fetch data of messages from an IMAP account. For example, I use the following command to retrieve the bodies of the messages with uid 1 to 4:

UID FETCH 1:4 BODY[]

Is there a way to fetch specific body parts for specific messages? For example, I would like to use something like:

UID FETCH (1 BODY[1.3]) (2 BODY[1.1]) (3 BODY[2.1]) (4 BODY[1.4])

PS: I know I could also send 4 distinct commands, but for performance reasons I can't afford to make a separate request for each message.


Solution

  • You have to retrieve the same bodyparts for each message. That is, if you want part 1 for messages 2 and 4 and part 2 for message 3, you cannot send fewer than two commands:

    a uid fetch 2,4 (body[1])
    b uid fetch 3 (body[3])
    

    The good news is that you can send them at the same time. So long as the commands don't conflict, you can send the second without waiting for the result of the first. Provided you can find a way to do that with Javamail.

    (Or perhaps body.peek[1], which is the same as body[] except that it doesn't set the \seen flag.)