The underlying connection was closed: An unexpected error occurred on a send on

12,610

Solution 1

My guess:

Exchange doesn't like the number of connections you are opening in a short amount of time and thinks it's under attack and subsequently blocking you from making more connections.

The first thing I would do is recode that "service". You don't want to instantiate a new one for each message. Just reuse the existing object. Also, send your messages one at a time to it.

Alternatively, speak with your Exchange administrator to see if they know how to reconfigure exchange to let your spam, I mean very important messages, through.. ;)

Solution 2

Let's see...

Works under debugger with breakpoints, doesn't work without.

Maybe you need to rate limit yourself.

Share:
12,610
AAK
Author by

AAK

Updated on June 05, 2022

Comments

  • AAK
    AAK almost 2 years

    I have a windows Service routine which is written in [C#].Net using VS 2010 which hits the DB once a day and if there are any records which need to be addressed. These record owners will be sent an email through the Exchange server. For the first few records the emails are sent fine but after may be 4rth or 5th Email I get an error as show

    Service failed at :System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. ---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
       at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
       at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
       --- End of inner exception stack trace ---
       at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
       at System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count)
       at System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
       at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
       at System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
       at System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
       at System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
       at System.Net.TlsStream.CallProcessAuthentication(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
       at System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
       at System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
       at System.Net.ConnectStream.WriteHeaders(Boolean async)
       --- End of inner exception stack trace ---
       at System.Net.HttpWebRequest.GetResponse()
       at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.Emit(HttpWebRequest& request)
       at Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ValidateAndEmitRequest(HttpWebRequest& request)
    

    If I debug the routine with break points it works fine. But when I run it without any break points I get the above error. Here is the snippet of code in which my routine sends emails:

    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
    lock (service)
    {
       if (service == null)
          throw new Exception("service is null");
       service.Credentials = new WebCredentials(data[0], data[1]);
       service.Url = new Uri("https://owa.CompanyName.com/ews/exchange.asmx");
       service.Timeout = 1200000;
       EmailMessage message = new EmailMessage(service);
       if (message == null)
           throw new Exception("message is null");
           message.Subject = "Test Email";
           message.Body = "This is a Test EMail Please use the below link to update ";
    
    //message.ToRecipients.Add(docList[0].CreatorEmailID);
           message.ToRecipients.Add("[email protected]");
           for (int j = 0; j < emailList.Count; j++)
           {
              message.CcRecipients.Add("[email protected]”);
           }
           System.Threading.Thread.Sleep(1000);
           ServicePointManager.ServerCertificateValidationCallback += ignoreCertCallback;
           try
           {
            message.Send();
           }
           finally
           {
           ServicePointManager.ServerCertificateValidationCallback -= ignoreCertCallback;
           }
    }
    

    I have used Microsoft Exchange WebService as a web reference here. I tried googling it but it didn’t really help me. I would be really happy if someone can help me on this issue.