EWS connection forcibly closed by remote host

2.1k Views Asked by At

I am using EWS to get attachments from an inbox. But from time to time I get the error.

[SocketException (0x2746): An existing connection was forcibly closed by the remote host]

enter image description here

I'm assuming that this is some sort of throttling that is going on the exchange side of things. So my question is. How can I change my code to properly handle this sort of error.

            string UserName = Properties.Settings.Default.UserName;
            string Password = Properties.Settings.Default.Password;
            string InboxEmail = Properties.Settings.Default.InboxEmail;
            string SavePath = Properties.Settings.Default.SavePath;
            int ItemViewCount = Properties.Settings.Default.ItemViewCount;
            bool moreItems = true;
            ItemId anchorId = null;

            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
            service.Credentials = new NetworkCredential(UserName, Password);

            service.Url = new Uri("https://myexchangeserver/EWS/Exchange.asmx");

            ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

            FolderId SharedMailbox = new FolderId(WellKnownFolderName.Inbox, InboxEmail);
            ItemView itemView = new ItemView(ItemViewCount + 1
                , 0);
            itemView.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);

            SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));

            FindItemsResults<Item> findResults;


            // we need to loop through the pages
            while (moreItems)
            {
                findResults = service.FindItems(SharedMailbox, searchFilter, itemView);

                anchorId = findResults.Items.First<Item>().Id;

                // do stuff here


                // see if more is available over the limit of 1k
                moreItems = findResults.MoreAvailable;

                if (moreItems)
                {
                    itemView.Offset += ItemViewCount;
                }

                // Set the flag to discontinue paging.
                if (!findResults.MoreAvailable)
                {
                    moreItems = false;
                }
            }
1

There are 1 best solutions below

0
On

I had the same issue. I was thinking it was an issue with a firewall or throttling. I finally found a weird workaround. When Exchange Web Services (EWS)’s FindItems keeps throwing exceptions, I open a browser and login to account on the web (I.e., on outlook.office365.com). That fixes issue for ~1 hour or more.

This is not only an EWS problem, but also an issue when Outlook cannot connect to the Exchange server. OWA login fixes the problem as well.