Java imap retrieve messages from date

I am writing / participating in receiving email using java from the IMAP folder using the javax.mail package. I was able to successfully receive the last n messages in the folder, however I am looking for an example to receive messages from a specified date. Any examples?

+7
java email imap
source share
5 answers

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

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

Some combination of the above should be the best way to get dates in a certain range.

+22
source share
 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); } } 
+5
source share

Instead of retrieving all messages, you should try using server-side search. This works using the javax.mail.Folder search method. You may have to write your own SearchTerm based on the criteria of Message.getReceivedDate ().

If server side search is not working, you can try using the fetch profile, i.e. use inbox.fetch instead of inbox.getMessages () (message [] msgs, FetchProfile fp). The javadoc for fetch says: Clients use this method to indicate that the specified elements are necessary for an array of a given range. Implementations are expected to extract these elements for a given range of messages in an efficient manner. Note that this method is just a hint of an implementation for pre-fetching the necessary elements.

+2
source share

Here is what I came up with. This works for me, but probably not the best way to do this. Any suggestions for improving 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()); } } 
0
source share

All letters for the last month:

  Calendar cal = Calendar.getInstance(); cal.roll(Calendar.MONTH, false); Message[] search = folder.search(new ReceivedDateTerm(ComparisonTerm.GT, cal.getTime())); 
0
source share

All Articles