I have set the Timeout property of SmtpClient class, but it doesn’t seem to work, when i give it a 1 millisecond value, the timeout actually is 15secs when the code is executed. The code i took from msdn.
string to = "jane@contoso.com";
string from = "ben@contoso.com";
string subject = "Using the new SMTP client.";
string body = @"Using this new feature, you can send an e-mail message from an application very easily.";
MailMessage message = new MailMessage(from, to, subject, body);
SmtpClient client = new SmtpClient("1.2.3.4");
Console.WriteLine("Changing time out from {0} to 100.", client.Timeout);
client.Timeout = 1;
// Credentials are necessary if the server requires the client
// to authenticate before it will send e-mail on the client's behalf.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
client.Send(message);
I tried the implementation on mono, it also doesn’t work.
Do anyone encountered the same problem?
Reproducing your test – it works for me
You asked if anyone has encountered the same problem – I just tried your code on Windows 7, VS 2008 with .NET 2.0 – it worked just fine. With the timeout set to
1, as you have it, I get this error almost immediately:I think the problem may be that you are expecting something different from timeout. Timeout means that the connection was made successfully, but the response did not come back from the server. This means you need to actually have a server listening on port 25 at your destination, but it doesn’t respond. For this test, I use Tcl to create a socket on 25 that did nothing:
When I changed the timout to
15000, I didn’t get the timeout error unti l5s later.Why Smtp.Timeout has no effect if the connection can’t be made
If nothing is listening at port 25, or the host is not reachable, the timeout is not going to happen until at least 20s, when the
system.net.tcpclientlayer times out. This is below thesystem.net.maillayer. From an excellent article describing the problem and solution:There is no ability to change that timeout from mail (which makes sense, mail servers are usually up), and in fact there’s no ability to change the connect from
system.net.socket, which is really surprising. But you can do an asynchronous connect, and can then tell if your host is up and the port open. From this MSDN thread, and in particular this post, this code works: