Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SmtpClient hangs with no exception thrown if wrong port was specified

I was trying to send emails in my Asp.Net C# application using port 465 with host "smtp.gmail.com" but the whole application hangs (keeps loading). When debugging it's stuck at SmtpClient.Send(msg).

Regardless of the credentials specified, it doesn't throw any exceptions to catch or any timeout errors. I have to close or refresh the page to regain access to the page.

If I put port 587 instead then every thing works fine and the SmtpClient.Send responds and sends the email or returns a proper exception such as operation timeout or failure sending email based on the credentials.

I simplified the code below for demonstration:

var smtp = new SmtpClient
                        {
                            Host = "smtp.gmail.com",
                            Port = 465,
                            EnableSsl = true,
                            Timeout = 200, // or any value it doesn't solve the problem
                            DeliveryMethod = SmtpDeliveryMethod.Network,
                            UseDefaultCredentials = false,
                            Credentials = new NetworkCredential("[email protected]", "password")
                        };

var msg = new MailMessage("[email protected]", "[email protected]", "Any subject", "Any body"); 
smtp.Send(msg); // stuck here
smtp.Dispose(); // never reached
msg.Dispose();

I tried SendAsync and reduced the timeout interval but this did not solve the problem. I think the problem is that smtp.gmail.com was reached but did not respond properly to port 465 and that's why the method was stuck.

I need to avoid such behavior since my application allows dynamic settings of the smtp server details and I don't want the whole application to hang in case of wrong details were entered.

Thank you,

enter image description here

like image 358
Osama Mortada Avatar asked Mar 20 '13 21:03

Osama Mortada


1 Answers

Found this answer in case anyone gets here

SmtpClient Timeout doesn't work

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IAsyncResult result = socket.BeginConnect("192.168.1.180", 25, null, null);
// Two second timeout
bool success = result.AsyncWaitHandle.WaitOne(2000, true);
if (!success) {
    socket.Close();
    throw new ApplicationException("Failed to connect server.");
}
like image 181
user2391759 Avatar answered Oct 10 '22 14:10

user2391759