查找异常的确切原因 - System.Net.Sockets.SocketException

时间:2013-12-30 18:42:32

标签: c# .net email

我尝试使用下面给出的代码将邮件发送到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)

此异常告诉我可能的原因列表 - 连接 尝试失败,因为关联方之后没有正确回复 一段时间,或建立的连接失败,因为连接主机 未能回应123.456.789:587

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

这是我用过的代码 - Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

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);

}

1 个答案:

答案 0 :(得分:0)

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

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