查找exception的确切原因 – System.Net.Sockets.SocketException

我尝试使用下面给出的代码将邮件发送到SMTP邮件服务器。 但是,我收到一个错误 –

Error: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> 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 123.456.789:587 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) 

此exception告诉我可能的原因列表 – 连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机无法响应123.456.789:587

但它并没有告诉我究竟是什么原因 – 端口号,错误的用户名,密码或其他东西。 我如何找出确切原因。

这是我使用的代码 – 从C#发送带附件的电子邮件,附件在Thunderbird中作为第1.2部分到达

 using System.Net; using System.Net.Mail; public void email_send() { MailMessage mail = new MailMessage(); SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); mail.From = new MailAddress("your mail@gmail.com"); mail.To.Add("to_mail@gmail.com"); mail.Subject = "Test Mail - 1"; mail.Body = "mail with attachment"; System.Net.Mail.Attachment attachment; attachment = new System.Net.Mail.Attachment("c:/textfile.txt"); mail.Attachments.Add(attachment); SmtpServer.Port = 587; SmtpServer.Credentials = new System.Net.NetworkCredential("your mail@gmail.com", "your password"); SmtpServer.EnableSsl = true; SmtpServer.Send(mail); } 

该IP地址显然不正确123.456.789:587
在命令提示符下尝试ping smtp.gmail.com以查看它是否正在解析该地址。 如果是这样,您可以在某处覆盖,可能在您的hosts文件中(C:\ Windows \ System32 \ drivers \ etc \ hosts)。

运行你的代码片段之后,我立即得到了Google的“登录尝试被阻止”,因为这种身份validation方法显然不符合他们当前的标准。