Search code examples
c#emailexchangewebservicesmanaged

How can I mark as read all emails fetched through EWS in a single update?


I followed the EWS Managed API example on MSDN to find all unread email in my Exchange mailbox account.

I later went through each found item in order to place them in the list I need to return while fetching the body of each message and updating each to IsRead=true as follows:

Folder.Bind(Service, WellKnownFolderName.Inbox);

SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And,
    new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
//ItemView limits the results to numOfMails2Fetch items
FindItemsResults<Item> foundItems = Service.FindItems(WellKnownFolderName.Inbox, sf,
    new ItemView(numOfMails2Fetch));

if (foundItems.TotalCount > 0)
{
    List<EmailMessage> emailsList = new List<EmailMessage>(foundItems.TotalCount);
    foundItems.Items.ToList().ForEach(item =>
    {
        var iEM = item as EmailMessage;
        emailsList.Add(iEM);
        // update properties
        iEM.IsRead = true;
        iEM.Update(ConflictResolutionMode.AutoResolve);
    });
    // fetches and assign the bodies of each email
    Service.LoadPropertiesForItems(emailsList,PropertySet.FirstClassProperties);
    return emailsList;
} else return null;

Is it possible to update all of the found items to IsRead=true in a single request instead? I.e. without updating them one by one = better performance and coherent logic.


Solution

  • Yes, you can. ExchangeService.UpdateItems is the method you want to use here. See How to: Process email messages in batches by using EWS in Exchange for details.