Search code examples
javaoffice365jakarta-mailimap

IMAP BEFORE search result is always empty with Office 365


I use this code to search through a Outlook 365 inbox programmatically:

Session session = Session.getDefaultInstance(new Properties());
Store store = session.getStore("imaps");
store.connect("outlook.office365.com", 993, EMAIL, PASSWORD);
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_WRITE);
Message[] messages = emailFolder.search(new ReceivedDateTerm(LT,
        Date.from(Instant.now().minus(14, DAYS))));

Therefore an IMAP BEFORE search is performed e.g. SEARCH BEFORE 16-Oct-2021 ALL but the returned messages array is always empty although there are thousands of mails older than 14 days. If a very short interval is used then there is a non-empty result.

Office 365 provides following capabilities

CAPABILITY IMAP4 IMAP4rev1 AUTH=PLAIN AUTH=XOAUTH2 SASL-IR UIDPLUS MOVE ID UNSELECT CLIENTACCESSRULES CLIENTNETWORKPRESENCELOCATION BACKENDAUTHENTICATE CHILDREN IDLE NAMESPACE LITERAL+

Are there any solutions and / or workaround to perform a server side search with dates like "older than" and "younger than" resp. using IMAP and Office 365 that works reliable?


Solution

  • After a longer correspondence with Microsoft Office 365 support this bug has been finally fixed by the exchange server team and rolled out in the night of 2022-01-21 CET.
    Now the IMAP SEARCH BEFORE command works as expected.

    Additionally we found out that SENTBEFORE and SENTSINCE are properly supported and return fast results even for thousands of messages while other IMAP email provider take several minutes for a result and similar amount of messages. They are supported by SentDateTerm in Jakara Mail client.

    While BEFORE, ON and SINCE refer to an unspecified internal date, use SENTBEFORE, SENTON and SENTSINCE the actual Date: header of the message.