I have a requirement to retrieve unread mails from Gmail. I am using Java Mail API. By default, this API retrieves mails from the oldest to newest. But I need to retrieve recent mails first. Is it possible? Thanks in advance.
Asked
Active
Viewed 3.8k times
4 Answers
42
Here is example. Do not forget to add javax.mail in your classpath.
import javax.mail.*;
import javax.mail.search.FlagTerm;
import java.util.*;
public class GmailFetch {
public static void main( String[] args ) throws Exception {
Session session = Session.getDefaultInstance(new Properties( ));
Store store = session.getStore("imaps");
store.connect("imap.googlemail.com", 993, "username@gmail.com", "password");
Folder inbox = store.getFolder( "INBOX" );
inbox.open( Folder.READ_ONLY );
// Fetch unseen messages from inbox folder
Message[] messages = inbox.search(
new FlagTerm(new Flags(Flags.Flag.SEEN), false));
// Sort messages from recent to oldest
Arrays.sort( messages, ( m1, m2 ) -> {
try {
return m2.getSentDate().compareTo( m1.getSentDate() );
} catch ( MessagingException e ) {
throw new RuntimeException( e );
}
} );
for ( Message message : messages ) {
System.out.println(
"sendDate: " + message.getSentDate()
+ " subject:" + message.getSubject() );
}
}
}

Dmitriy Dobrotvorskiy
- 820
- 7
- 10
8
Make sure to use the IMAP protocol, as it supports for flagging.
Do following changes to your code:
- replace
inbox.open( Folder.READ_ONLY );
byinbox.open( Folder.READ_WRITE );
Then after reading the message, set the flag like so:
message.setFlag(Flags.Flag.SEEN, true);
Full example:
import javax.mail.*;
import javax.mail.search.FlagTerm;
import java.util.*;
public class GmailFetch {
public static void main( String[] args ) throws Exception {
Session session = Session.getDefaultInstance(new Properties( ));
Store store = session.getStore("imaps");
store.connect("imap.googlemail.com", 993, "username@gmail.com", "password");
Folder inbox = store.getFolder( "INBOX" );
inbox.open( Folder.READ_WRITE );
// Fetch unseen messages from inbox folder
Message[] messages = inbox.search(
new FlagTerm(new Flags(Flags.Flag.SEEN), false));
// Sort messages from recent to oldest
Arrays.sort( messages, ( m1, m2 ) -> {
try {
return m2.getSentDate().compareTo( m1.getSentDate() );
} catch ( MessagingException e ) {
throw new RuntimeException( e );
}
} );
for ( Message message : messages ) {
System.out.println(
"sendDate: " + message.getSentDate()
+ " subject:" + message.getSubject() );
message.setFlag(Flags.Flag.SEEN, true);
}
}
}

Jonas_Hess
- 1,874
- 1
- 22
- 32

sangamesh
- 81
- 1
- 1
-
Why is this needed? There is an accepted answer which is three years old... – Nico Haase Jan 22 '18 at 12:42
-
1I agree with you @NicoHaase, I think this poster was trying to say you should set the `SEEN` flag as true so that it is marked as read so that the message isn't requested the next time this program runs. – JRSofty Apr 19 '18 at 12:06
-
How to fetch unread mails only, seems search method is not accepting the Flag now. – Syam Danda Jun 14 '18 at 06:39
3
I think this might help to access read/unread/recent mails change your variables according to your needs.
// search for all "unseen" messages
Flags seen = new Flags(Flags.Flag.SEEN);// try changing this SEEN to RECENT
// set it true or false for seen & unseen mail
FlagTerm unseenFlagTerm = new FlagTerm(seen, false)
Message messages[] = inbox.search(unseenFlagTerm);

Vikash Kumar
- 1,096
- 11
- 10
2
JavaMail gives you an array of Message objects. The messages are in the order received. If you want to look at the most recently received messages first, go through the array in the reverse order. If you want to look at the most recently sent messages first, you'll need to sort the array, as described in the other answer.

Bill Shannon
- 29,579
- 6
- 38
- 40
-
I think I know what his problem is. At least it sounds like one I had: If you want to update the screen promptly upon user action, then most IMAP servers' FETCH response order is not good. "Highest UID first" would be better than "lowest UID first". But this is not something Javamail can solve. – arnt Feb 24 '15 at 08:18