1

I have seen many examples of sending email from c# code, i am following the most popular method of using System.Net.Mail.SmtpClient. I am able to send the mail for the first time but after that it gives an error saying A connect request was made on an already connected socket.

I am using the following code to send the mail :

using (MailMessage mail = new MailMessage())
{
    using (SmtpClient mailer = new SmtpClient("smtp.server.com"))
    {
        Console.Write("Sending mails...");
        mail.From = new MailAddress("from@mail.com");
        mail.To.Add("myaddress@mail.com");
        mail.Subject = "test-subject";
        mail.Body = "test-body";
        mailer.Port = 25;
        mailer.Credentials = new System.Net.NetworkCredential("from@mail.com", "from-password");
        mailer.EnableSsl = true;
        try
        {
            mailer.Send(mail);
            Console.WriteLine("Mail sent");
        }
        catch (Exception e)
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("\rCannot send mail, an error occured : {0}", e);
            Console.ResetColor();
        }
    }
}

Error message is :

Cannot send mail, an error occured : System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connect request was made on an already connected socket 200.200.200.200:25
   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, Int32 timeout, 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, Int32 timeout)
   at System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback)
   at System.Net.PooledStream.Activate(Object owningObject, 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.SmtpTransport.GetConnection(ServicePoint servicePoint)
   at System.Net.Mail.SmtpClient.GetConnection()
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   --- End of inner exception stack trace ---
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at TestApp.Program.Main(String[] args) in D:\Desktop\TestApp\TestApp\Program.cs:line 290

As you can see, i have kept instances of both MailMessage and SmptClient inside using clause so that if any error occurs, the connection will be closed automatically. But it sends the mail for first time after boot correctly and fails all the other attempts afterwards.

The SMTP server is behind a proxy and the firewall client is running on my system. Proxy is not a problem, here as far as i think.

Is there any error in the code? How can i make it to work?

I have tried using the Outlook API but that requires authentication from the user before sending every mail. I do not want this behaviour.

PS : I have removed some details like IP address and server name which are irrelevant in this case.

Thanks in advance :)

ruhil
  • 151
  • 2
  • 5

1 Answers1

1

Probably you should upgrade to NET 4.0. This question on Microsoft Connect explain that the SMTPClient doesn't close correctly the connection and this problem has been fixed in 4.0

Someone has had some success using the property MaxIdleTime set to 1, but in any case it seems that the problem is only moved forward, when the number of connections exceeds the amount allowed by the mail server.

Steve
  • 213,761
  • 22
  • 232
  • 286
  • Thanks for your help, but i cannot upgrade to *.NET 4.0*. Is there any work around? Could you please elaborate about **MaxIdleTimeOut**? – ruhil Jul 02 '12 at 15:57
  • @SandeepRuhil sorry for the confusion, the property is **MaxIdleTime**, [here some references](http://connect.microsoft.com/VisualStudio/feedback/details/337557/smtpclient-does-not-close-session-after-sending-message). In the meantime I have found [this question](http://stackoverflow.com/questions/930236/net-best-method-to-send-email-system-net-mail-has-issues) on SO that suggest to set the value of MaxIdleTime = 2 to avoid CPU 100% utilization – Steve Jul 02 '12 at 16:08