简体   繁体   中英

Finding the exact cause for the exception - System.Net.Sockets.SocketException

I tried to send a mail to an SMTP mail server using the code given below. But, I am getting an error -

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)

This exception tells me the possible list of causes - 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

But it does not tell me exactly what is the cause - port number, wrong username, password or something else. How do I find out what is the exact cause.

Here is the code I used - 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);

}

That IP address is obviously not correct 123.456.789:587 .
Try ping smtp.gmail.com in a command prompt to see if it is resolving to that address. If so, you have that overriden somewhere, perhaps in your hosts file (C:\\Windows\\System32\\drivers\\etc\\hosts).

After running your snippet ran but then I immediately got a "Sign-in attempt prevented" from Google since this method of authentication apparently does not meet their current standards.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM