Search code examples
c#web-servicesexchangewebservicesmicrosoft-exchange

Microsoft.Exchange.WebServices : Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host


I am trying to save email on office 365 using Microsoft.Exchange.WebServices.dll (EWS Apis)

     EmailMessage f_ObjEWSMail  = new EmailMessage(objExchangeService);
     f_ObjEWSMail.Save(p_objFoderID); // Throwing error here

It throws exception randomly :

Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

at System.Net.Security._SslStream.EndRead(IAsyncResult asyncResult)

at System.Net.TlsStream.EndRead(IAsyncResult asyncResult)

at System.Net.PooledStream.EndRead(IAsyncResult asyncResult)

at System.Net.Connection.ReadCallback(IAsyncResult asyncResult)

or sometimes it throws:

The request failed. The underlying connection was closed: An unexpected error occurred on a receive.

Stack Strace :: at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.GetEwsHttpWebResponse(IEwsHttpWebRequest request) at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ValidateAndEmitRequest(IEwsHttpWebRequest& request) at Microsoft.Exchange.WebServices.Data.MultiResponseServiceRequest1.Execute() at Microsoft.Exchange.WebServices.Data.ExchangeService.InternalCreateItems(IEnumerable1 items, FolderId parentFolderId, Nullable1 messageDisposition, Nullable1 sendInvitationsMode, ServiceErrorHandling errorHandling) at Microsoft.Exchange.WebServices.Data.Item.InternalCreate(FolderId parentFolderId, Nullable1 messageDisposition, Nullable1 sendInvitationsMode) at Microsoft.Exchange.WebServices.Data.Item.Save(FolderId parentFolderId) at Office365EWSWriter.Office365Engine.SaveMail(EmailMessage p_objEWSMailItem, FolderId p_objFoderID)

Please suggest solution.


Solution

  • Those errors are due to issues with the underlying transport connectivity (eg your network connection to the cloud) because your dealing with the cloud you can't guarantee the network 100% (eg vs Onprem where you just connecting to the server over a switch). All you can do in this instance is catch the error and retry. The EWS Managed API is using HttpWebRequest to send and receive the SOAP packets so these errors are generated by this class at the client (if you want to chase those errors further then i would suggest searching Stackoverflow for those errors on that class). If you try using your code from a cloud based Virtual Machine (or service) like AWS or Azure you should find the instances of these errors a lot lower because the underlying network connectivity is much more reliable.