How to Delete Old Emails in MS Exchange Using EWS

|

Background

I work within a corporate environment that manages its own Microsoft Exchange Server. I am also on a development team and receive thousands of automated email messages per day from various services that run across multiple servers. I started out creating rules for these emails in MS Outlook that sorted them into folders based on the service that generated them. I would go in once a day and clean out the folders. This is a bit tedious. Additionally, I want to keep emails that are within the last day in case something goes wrong with that service and I need to reference an email that was generated. Even more tedious.

Next I thought to myself, “Why don’t I use the built-in Outlook Archive method?” That would be a great option, but my company manages our archive policies, meaning I cannot modify them.

Finally, having all other avenues closed to me, I decided to write my own utility to perform this task. I am, after all, a Software Engineer.

Solution

In your Visual Studio project, add a NuGet reference to Microsoft.Exchange.WebServices by Microsoft. And yes, this post assumes that you’re using Visual Studio.

Add a using clause to the top of your code file.

using Microsoft.Exchange.WebServices.Data;

For this example I am going to assume that we are logged into a corporate domain (client-side) and we are connecting to our corporate MS Exchange Server that is hosted on the same domain. Create an ExchangeService object and instruct it to auto-discover the web services URL.

string MY_EMAIL_ADDRESS = "put.your.actual@email.address.here";

// Connect to Exchange as a user logged into the same domain as the Exchange server
ExchangeService service = new ExchangeService();
service.UseDefaultCredentials = true;
service.AutodiscoverUrl(
        MY_EMAIL_ADDRESS,
        RedirectionUrlValidationCallback);
Console.WriteLine("Autodiscovered URL : {0}", service.Url);

Connect to the INBOX and list how many emails are present. Why list how many emails are in the INBOX? Well… because it’s cool… and we can!

// Open the INBOX
Folder fInbox = Folder.Bind(service, WellKnownFolderName.Inbox);
Console.WriteLine("Found {0} items in the INBOX", fInbox.TotalCount);

If you want to process emails in the INBOX, then you can just use the proper search criteria to find the items and begin processing. However, if you would like to process a sub-folder, you’ll need to search and find that first.

// Find sub-folder for filtered emails
Folder fFiltered = service.FindFolders(
        fInbox.Id,
        new SearchFilter.IsEqualTo(
                FolderSchema.DisplayName,
                "Filtered"),
        new FolderView(1)).FirstOrDefault();

Now you need to create a search criteria to find the items you would like to delete. In my case, a simple date search sufficed.

// Find email items at least 1 day old
TimeSpan tsOneDay = new TimeSpan(1, 0, 0, 0);
FindItemsResults<Item> oldItems = fFiltered.FindItems(
        new SearchFilter.IsLessThanOrEqualTo(
                ItemSchema.DateTimeReceived,
                DateTime.Now.Subtract(tsOneDay)),
        new ItemView(1000));
Console.WriteLine("Found [{0}] old items", oldItems.TotalCount);

Finally, loop through all of the old items and delete them. For my purposes, I decided to use the Delete Mode that just moved the items into my “Deleted Items” folder. That way if something went wrong I could still retrieve the deleted emails.

// Delete old items (put them into the Trash)
foreach (Item item in oldItems)
{
    Console.WriteLine("Deleting : {0}", item.Subject);
    item.Delete(DeleteMode.MoveToDeletedItems);
}

Source Code

If you would like the full source code to the example above, you may grab it at this Github repository: https://github.com/franzone/TestEWS

If you would like to download a fully(ish) working console program/utility built using these methods, you may grab that at this Github repository: https://github.com/franzone/CleanupMyMailbox

References