[英]Finding the exact cause for the 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)
此異常告訴我可能的原因列表-連接嘗試失敗,因為一段時間后連接方未正確響應,或者連接建立失敗,因為連接的主機未能響應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處收到了“阻止登錄嘗試”的通知,因為這種身份驗證方法顯然不符合其當前標准。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.