gpt4 book ai didi

c# - SmtpClient 超时不起作用

转载 作者:太空狗 更新时间:2023-10-29 17:39:26 26 4
gpt4 key购买 nike

我已经设置了 SmtpClient 类的超时属性,但它似乎不起作用,当我给它一个 1 毫秒的值时,执行代码时超时实际上是 15 秒。我从 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);

我试过在单声道上实现,它也不起作用。

有人遇到过同样的问题吗?

最佳答案

重现你的测试 - 它对我有用

您询问是否有人遇到过同样的问题 - 我刚刚在 Windows 7、VS 2008 和 .NET 2.0 上尝试了您的代码 - 它工作得很好。将超时设置为 1,如您所见,我几乎立即收到此错误:

Unhandled Exception: System.Net.Mail.SmtpException: The operation has timed out
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at mailtimeout.Program.Main(String[] args) in c:\test\mailtimeout\Program.cs:line 29

我认为问题可能出在您期待与超时不同的东西。超时表示连接成功,但服务器没有返回响应。这意味着您实际上需要有一台服务器在目的地的端口 25 上监听,但它没有响应。对于此测试,我使用 Tcl在 25 上创建一个什么都不做的套接字:

c:\> tclsh
% socket -server foo 25

当我将超时更改为 15000 时,直到 l5s 之后我才收到超时错误。

为什么连接不上时Smtp.Timeout没有作用

如果端口 25 没有任何监听,或者主机不可访问,超时至少要到 20 秒才会发生,此时 system.net.tcpclient 层超时。这是在 system.net.mail 层之下。来自excellent article describing the problem and solution :

You will notice that neither of the two classes, System.Net.Sockets.TcpClient nor System.Net.Sockets.Socket has a timeout to connect a socket. I mean a timeout you can set. .NET Sockets do not provide a Connect Timeout when calling the Connect/BeginConnect method while establishing a Synchronous/Asynchronous socket connection. Instead, connect is forced to wait a very long time before an Exception is thrown if the server it tried to connect to is not listening or if there is any network error. The default timeout is 20 - 30 seconds.

没有能力改变邮件的超时(这是有道理的,邮件服务器通常是正常的),事实上没有能力改变 system.net.socket 的连接,它真是令人惊讶。但是您可以进行异步连接,然后可以判断您的主机是否启动以及端口是否打开。来自 this MSDN thread ,特别是 this post ,此代码有效:

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.");
}

关于c# - SmtpClient 超时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10467476/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com