tags:

views:

800

answers:

4

I am writing/learning to fetch email using java from an IMAP folder using javax.mail package. I was successfully able to retrieve the last n messages in a Folder, however I am looking to build an example to retrieve messages since a specified date. Any examples?

A: 

Here is what I came up with. This works for me, but probably not the best way to go about it. Any suggestions to improve this?

      Date from; //assume initialized
      Store store; //assume initialized
      Folder inbox = store.getFolder("INBOX");
      inbox.open(Folder.READ_ONLY);
      int end = inbox.getMessageCount();
      long lFrom = from.getTime();
      Date rDate;
      long lrDate;
      int start = end;
      do {
        start = start - 10;
        Message testMsg = inbox.getMessage(start);
        rDate = testMsg.getReceivedDate();
        lrDate = rDate.getTime();
      } while (lrDate > lFrom);
      Message msg[] = inbox.getMessages(start, end);
      for (int i=0, n=msg.length; i<n; i++) {
        lrDate = msg[i].getReceivedDate().getTime();
        if (lrDate > lFrom) {
          System.out.println(i + ": "
            + msg[i].getFrom()[0]
            + "\t" + msg[i].getSubject());
        }
      }
Chaitan
+1  A: 

Instead of fetching all messages you should try taking advantage of server side search. This works by using the search method of javax.mail.Folder. You will probably have to write your own SearchTerm based on a criteria on Message.getReceivedDate().

If server side search does not work, you could try using a fetch profile, i.e. instead of inbox.getMessages() use inbox.fetch(Message[] msgs, FetchProfile fp). The javadoc for fetch says: Clients use this method to indicate that the specified items are needed en-masse for the given message range. Implementations are expected to retrieve these items for the given message range in a efficient manner. Note that this method is just a hint to the implementation to prefetch the desired items.

diciu
+1  A: 

You could also use the SearchTerm classes in the java mail package.

SearchTerm olderThen = new ReceivedDateTerm(ComparisonTerm.LT, someFutureDate);
SearchTerm newerThen = new ReceivedDateTerm(ComparisonTerm.GT, somePastDate);
SearchTerm andTerm = new AndTerm(olderThen, newerThen);
inbox.search(andTerm);

Some combination of the above should prove to be a better way to get dates within a certain range.

A: 

public class CheckDate { public void myCheckDate(Date givenDate) { SearchTerm st = new ReceivedDateTerm(ComparisonTerm.EQ,givenDate);

     Message[] messages = inbox.search(st);

}

// in main method

public static void main(String[] args) throws ParseException{ SimpleDateFormat df1 = new SimpleDateFormat( "MM/dd/yy" ); String dt="06/23/10"; java.util.Date dDate = df1.parse(dt); cd.myCheckDate(dDate); }

Javed Ahmed