none
System.Net.Mail.SmtpException occurs randomly while sending emails C# MVC RRS feed

  • Question

  • Hi,
    I am facing a strange problem. I have a small application that sends email to the specified user. When the email is sent, one at a time after an interval of few minutes(1 min or more), the emails are sent successfully. But if the emails are sent quickly one after the other, within seconds, it throws an error. There is no specific pattern for this error. Because sometimes connection cannot be made, while sometimes, it is done successfully.
    This is an MVC application and it is hosted on an AWS server. I am facing this same issue for twoseparate applications hosted on different AWS servers.
    I use the following code to send the mail:
                    SmtpClient client = new SmtpClient();
                    client.Host = host;
                    client.Port = Port;
                    client.EnableSsl = false;

                    System.Net.NetworkCredential SMTPUserInfo;
                    SMTPUserInfo = new System.Net.NetworkCredential(Username, Password);
                    client.UseDefaultCredentials = false;
                    client.Credentials = SMTPUserInfo;
                   
                    client.Send(eMsg);
                    return strSentMail.ToString();
    I get the following error:
    System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond xx.xx.xx.xx:xx
       at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
       at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
       --- End of inner exception stack trace ---
       at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6)
       at System.Net.PooledStream.Activate(Object owningObject, Boolean async, GeneralAsyncDelegate asyncCallback)
       at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
       at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
       at System.Net.Mail.SmtpClient.Send(MailMessage message)
       --- End of inner exception stack trace ---
       at System.Net.Mail.SmtpClient.Send(MailMessage message)
       at IMS.Web.Helper.MailHelper.SendMail(String sendto, String cc, String bcc, String from, String subject, String body)
    Tuesday, September 10, 2013 5:53 AM

Answers

  • Hi Opspl ,
    I do a test on my machine  and  discover that  SMTP server limits the number of clients that connect to the server simultaneously.While our client is sending email to the SMTP server  continuously, maybe there will be a connection exceptions appears.So i would like to suggest you to add retry mechanism,if one email can't  send successfully,you can try to send more times.
    In addition,every time  after sending one email ,wait a  few minutes.The detailed code are shown in the following:
    int RETRY_CEILING = 3;
    using (SmtpClient client = new SmtpClient())
    {
    	client.Host =  host;
    	client.Port = port;
    	client.EnableSsl = false;
    
    	client.ServicePoint.MaxIdleTime = 0;
    	client.ServicePoint.ConnectionLimit = 1;
    
    	System.Net.NetworkCredential SMTPUserInfo;
    	SMTPUserInfo =new System.Net.NetworkCredential(Username, Password);
    	client.UseDefaultCredentials = false;
    	client.Credentials = SMTPUserInfo;
    	
    	for(int i = 0; i < RETRY_CEILING; ++i)
    	{
    		try
    		{
    			client.Send(eMsg);
    		}catch(Exception e)
    		{
    			continue;
    		}
    		break;
    	}
    	//client.Dispose();
    }
    
    Hope these help.

    Lilia Gong <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Wednesday, September 25, 2013 3:49 PM
    Moderator

All replies

  • What's the exception StatusCode you are getting ?

    Josip Habjan      http://habjan.blogspot.com

    Tuesday, September 10, 2013 6:50 AM
  • Perhaps you could use a Task to send each e-mail message (fire and forget).

    Tuesday, September 10, 2013 9:11 AM
  •  

    Hello, 

    Thanks for your posting.

    From your description, I know that you encounter some issue  when application sends email to the specified user. Based on my experience ,the main reason  is that client object  that Occupied the connection  can’t be released .

    SMTPClient has a property named ServicePoint http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx .

    By setting ServicePoint.MaxIdleTime Property http://msdn.microsoft.com/en-us/library/system.net.servicepoint.maxidletime.aspx  to 1 will help to close the connection immediately.

    In addition, I think that you  can use  "using" statement  that  is to ensure that the object is always disposed correctly .The  detailed code are shown in the following:

                 using(SmtpClient client = new SmtpClient())

                    {

                    client.Host = host;

                    client.Port = Port;

                    client.EnableSsl = false;

                    System.Net.NetworkCredential SMTPUserInfo;

                    SMTPUserInfo = new System.Net.NetworkCredential(Username, Password);

                    client.UseDefaultCredentials = false;

                    client.Credentials = SMTPUserInfo;               

                    client.Send(eMsg);

                  } 

    Hope these help.


    Lilia Gong <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Wednesday, September 11, 2013 2:55 PM
    Moderator
  • Hello Josip,

    As this error occurs sporadically, I wrote the exception in the ErrorLog file. The error that I posted is all that I get. So can't figure out the StatusCode

    Thanks,

    Opspl

    Friday, September 13, 2013 4:14 AM
  • Thanks for your reply Lilia,

    I had also tried this code. Also had added a dispose, before implementing 'using'. When I tried 'using' I commented the dispose statement. It works fine initially, but later as the number of mails increase, it starts giving error randomly. If the email was successfully delivered for one user at one time, the next time it got an error. But not in any particular pattern

     using (SmtpClient client = new SmtpClient())
                            {
                                client.Host =  host;
                                client.Port = port;
                                client.EnableSsl = false;

                                client.ServicePoint.MaxIdleTime = 0;
                                client.ServicePoint.ConnectionLimit = 1;

                                System.Net.NetworkCredential SMTPUserInfo;
                                SMTPUserInfo =new System.Net.NetworkCredential(Username, Password);
                                client.UseDefaultCredentials = false;
                                client.Credentials = SMTPUserInfo;

                                client.Send(eMsg);
                                //client.Dispose();
                            }

    Friday, September 13, 2013 4:46 AM
  • Hi Opspl ,
    I do a test on my machine  and  discover that  SMTP server limits the number of clients that connect to the server simultaneously.While our client is sending email to the SMTP server  continuously, maybe there will be a connection exceptions appears.So i would like to suggest you to add retry mechanism,if one email can't  send successfully,you can try to send more times.
    In addition,every time  after sending one email ,wait a  few minutes.The detailed code are shown in the following:
    int RETRY_CEILING = 3;
    using (SmtpClient client = new SmtpClient())
    {
    	client.Host =  host;
    	client.Port = port;
    	client.EnableSsl = false;
    
    	client.ServicePoint.MaxIdleTime = 0;
    	client.ServicePoint.ConnectionLimit = 1;
    
    	System.Net.NetworkCredential SMTPUserInfo;
    	SMTPUserInfo =new System.Net.NetworkCredential(Username, Password);
    	client.UseDefaultCredentials = false;
    	client.Credentials = SMTPUserInfo;
    	
    	for(int i = 0; i < RETRY_CEILING; ++i)
    	{
    		try
    		{
    			client.Send(eMsg);
    		}catch(Exception e)
    		{
    			continue;
    		}
    		break;
    	}
    	//client.Dispose();
    }
    
    Hope these help.

    Lilia Gong <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Wednesday, September 25, 2013 3:49 PM
    Moderator