使用android中的javamail根据日期时间检索电子邮件

Ric*_*cky 3 android jakarta-mail

我正在完成检索电子邮件的任务.我设法使用以下代码检索.但是,它从gmail收件箱中的最早到最新的电子邮件中检索收到的电子邮件.有没有办法让它检索到最新的邮件?我打算实现一种方法来检索最新的20封邮件,而不是检索收件箱中的所有邮件.提前感谢您的指导.

public ArrayList<HashMap<String, String>> getMail(int inboxList){
        Folder inbox;
         /*&nbsp; Set the mail properties&nbsp; */
         Properties props = System.getProperties();
         props.setProperty("mail.store.protocol", "imaps");
         try
         {
             /*&nbsp; Create the session and get the store for read the mail. */
             Session session = Session.getDefaultInstance(props, null);
             Store store = session.getStore("imaps");
             store.connect("imap.gmail.com",username, password);

             /*&nbsp; Mention the folder name which you want to read. */
             inbox = store.getFolder("Inbox");
             System.out.println("No of Unread Messages : " + inbox.getUnreadMessageCount());
             /*Open the inbox using store.*/
             inbox.open(Folder.READ_WRITE);
             /*&nbsp; Get the messages which is unread in the Inbox*/
             Message messages[];
             if(recent){
                 messages = inbox.search(new FlagTerm(new Flags(Flag.RECENT), false));
             }else{
                 messages = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
             }

             /* Use a suitable FetchProfile&nbsp;&nbsp;&nbsp; */
             FetchProfile fp = new FetchProfile();
             fp.add(FetchProfile.Item.ENVELOPE);
             fp.add(FetchProfile.Item.CONTENT_INFO);
             inbox.fetch(messages, fp);

             try
             {
                 printAllMessages(messages);
                 inbox.close(true);
                 store.close();
             }
             catch (Exception ex)
             {
                 System.out.println("Exception arise at the time of read mail");
                 ex.printStackTrace();
             }
         }
         catch (NoSuchProviderException e)
         {
             //e.printStackTrace();

             System.exit(1);

         }
         catch (MessagingException e)
         {
             //e.printStackTrace();

             System.exit(2);
         }
Run Code Online (Sandbox Code Playgroud)

小智 10

而不是inbox.search()使用

 inbox.getMessages(int start,int end);
Run Code Online (Sandbox Code Playgroud)

它将检索消息范围.

要获取最新的20封邮件,请使用:

int n=inbox.getMessageCount();
messages= inbox.getMessages(n-20,n);
Run Code Online (Sandbox Code Playgroud)