2

I am trying to read the emails i have received today only using the javax.mail api.

Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);

ReceivedDateTerm term = new ReceivedDateTerm(ComparisonTerm.EQ,new Date(Calendar.DAY_OF_MONTH));

Message[] messages = emailFolder.search(term);

The above code does not return any emails even though i do have in my inbox.

Paul Lemarchand
  • 2,068
  • 1
  • 15
  • 27

3 Answers3

1

It seems that the Date constructor takes in a long which represents the milliseconds from January 1st, 1970. However, Calender.DAY_OF_MONTH seems to only return an integer representing the day of the month. I would recommend using something such as System.currentTimeMillis() to derive the date in millis.

References:

https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#Date-long-

https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#currentTimeMillis--

What's the difference between adding DAY_OF_MONTH or DAY_OF_YEAR to a Calendar object?

akliyen
  • 11
  • 4
1

Caveat: I do not know JavaMail, and don’t understand the exact behavior of ReceivedDateTerm. But I do know date-time handling. If the goal is determine the first moment of today, read on.

First moment of day

Your date-time handling is incorrect.

The modern approach uses the java.time classes defined in JSR 310.

Getting the current date requires a time zone. For any given moment, the date varies around the globe by zone.

ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
LocalDate today = LocalDate.now( z ) ;

Determine the first moment. Not necessarily the time 00:00:00 as some dates in some zones start at another time such as 01:00:00.

ZonedDateTime zdt = today.atStartOfDay( z ) ;

Extract an Instant to adjust into UTC. Same moment, same point on the timeline, different wall-clock time.

Instant instant = zdt.toInstant() ;

The constructor for ReceivedDateTerm takes a java.util.Date object, having not yet been updated to the modern java.time framework.

Convert from our modern Instant to the terrible and misnamed legacy class java.util.Date.

Date d = Date.from( instant ) ;

Pass d to your JavaMail code as the starting moment for your search.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

Could you try

ReceivedDateTerm term = new ReceivedDateTerm(ComparisonTerm.EQ,new Date(Calendar.getTime()));

or

SimpleDateFormat format= new SimpleDateFormat( "MM/dd/yy" );
java.util.Date dDate = format.parse("01/01/19");
SearchTerm st = new ReceivedDateTerm(ComparisonTerm.EQ,dDate );
J_D
  • 740
  • 8
  • 17
Tony Toms
  • 11
  • 3