Search code examples
c#windowsexceptionserviceexchangewebservices

System.OutOfMemoryException thrown when gathering emails using Exchange Web Server API


I'm getting the following error in my windows service source code:

System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' 
was thrown.
at System.Collections.Generic.List`1.set_Capacity(Int32 value) at 
System.Collections.Generic.List`1.EnsureCapacity(Int32 min) at 
System.Collections.Generic.List`1.Add(T item)

when I try to load in the emails from an inbox using Exchange Web Server API. Below is the code used to authenticate and read from the mailbox:

ExchangeService service = new 
ExchangeService(ExchangeVersion.Exchange2013_SP1);
service.Credentials = new WebCredentials("name@domain.co.uk", "*****");
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.AutodiscoverUrl("name@domain.co.uk", RedirectionUrlValidationCallBack);

//retrieve first 50 emails
int offset = 0;
int pageSize = 50;
bool moreEmails = true;
ItemView view = new ItemView(pageSize, offset, OffsetBasePoint.Beginning);

view.PropertySet = PropertySet.IdOnly;
FindItemsResults<Item> findResults;
List<EmailMessage> emails = new List<EmailMessage>();
findResults = service.FindItems(WellKnownFolderName.Inbox, view);

while (moreEmails)
{
    foreach (var item in findResults.Items)
    {
        emails.Add((EmailMessage)item);
    }

    moreEmails = findResults.MoreAvailable;

    if (moreEmails)
    {
        view.Offset += pageSize;
    }
}

 PropertySet properties = (BasePropertySet.FirstClassProperties);
 service.LoadPropertiesForItems(emails, properties);

I'm being told the error is located at

emails.Add((EmailMessage)item);

but I'm unsure how to go about resolving this error. Any help is much appreciated.


Solution

  • Slide the call to FindItems inside your while loop. Without it you are simply adding the same items to your collection until memory runs out.

    while (moreEmails)
    {
        findResults = service.FindItems(WellKnownFolderName.Inbox, view);
    
        foreach (var item in findResults.Items)
        {
            emails.Add((EmailMessage)item);
        }
    
        moreEmails = findResults.MoreAvailable;
    
        if (moreEmails)
        {
            view.Offset += pageSize;
        }
    }