JavaMail使用IMAP阅读最近未读的邮件
问题描述:
我需要从Gmail检索未读邮件。我正在使用Java Mail API。默认情况下,此API检索从最旧到最新的邮件。但我需要先检索最近的邮件。可能吗?在此先感谢。
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.
答
以下是示例。不要忘记在类路径中添加 javax.mail 。
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() );
}
}
}