Search code examples
javaexchangewebservicesewsjavaapi

EWS Java how to find emails older than xx days and Delete all in one shot


I want to find items in a folder which are older than xx days and Delete all the items found in one shot. I was able to find the items matching my criteria. here is my code.

import org.joda.time.DateTime;
int purgeDays = 14;

    try {

        ItemView view = new ItemView(Integer.MAX_VALUE);

        Folder purgeFolder = Folder.bind(service, folderId);

        // need to convert to get Mon Sep 12 16:31:27 CDT 2016
        SearchFilter searchFilter = new SearchFilter.IsLessThanOrEqualTo(ItemSchema.DateTimeReceived, (DateTime.now().minusDays(purgeDays).toDate()));

        FindItemsResults<Item> emailsToPurge = service.findItems(purgeFolder.getId(), searchFilter, view);

        if (emailsToPurge != null && emailsToPurge.getItems() != null && emailsToPurge.getTotalCount() > 0 ) {

           // want something to delete all items at once
           emailsToPurge.deleteAll();

        } else {
            log.info("Found no emails to purge for Mailbox-"+ userName);
        }

    } catch (Exception e) {
        log.error("Exception "+ e.getMessage());
    }

Solution

  • Have a look at the deleteItems method on the ExchangeService class https://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.exchangeservice.deleteitems(v=exchg.80).aspx this allows you to send a batch DeleteItem request. I would suggest you page your deletes though at no more than 1000 items at a time else you may have issue with throttling and/or the requests timing out.