Search code examples
c#exchangewebservices

C# EWS Save all Email Found in Inbox Into an Item List


My current code accesses all unread email in Inbox. However, as this is a method which will return the list of emails for further processing for each email.

I am unsure of how to group the emails found into a list or table.

Any advice will be greatly appreciated.

private static GetNewEmailInInbox(ExchangeService service, int batch, string autoDiscoverURL)
{
    if (service != null)
    {
        Console.WriteLine("Accessing system account mailbox...");

        TimeSpan ts = new TimeSpan(0, -1, 0, 0);
        DateTime date = DateTime.Now.Add(ts);
        service.AutodiscoverUrl(autoDiscoverURL);
        SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));

        FindItemsResults<Item> emailItemList;
        ItemView view = new ItemView(50);
        int inboxCount = 1;
        do
        {
            emailItemList = service.FindItems(WellKnownFolderName.Inbox, sf, view);
            foreach (var emailItem in emailItemList.Items)
            {
                Console.WriteLine(inboxCount + ". " + emailItem.Subject);
                inboxCount++;

                //add this email to an allEmailList
            }

            if (!emailItemList.NextPageOffset.HasValue)
                break;
        }
        while (emailItemList.MoreAvailable);
    }
return allEmailList;
}

Solution

  • You can group the emails using an IList Interface.

    IList<T> allEmailList = new List<T>();
    
    FindItemsResults<Item> emailItemList = service.FindItems(WellKnownFolderName.Inbox, sf, view);
    foreach (var emailItem in emailItemList.Items.OfType<T>())
    {
        Console.WriteLine(inboxCount + ". " + emailItem.Subject);
        inboxCount++;
    
        //add this email to an allEmailList
        allEmailList.Add(emailItem);
    }