1

I was trying to send an email using smtp.gmail.com with below code (WPF - C#).

Can someone please let me know what is wrong here.

SmtpClient smtpServer = new SmtpClient("smtp.gmail.com");

smtpServer.Port = 587;
smtpServer.UseDefaultCredentials = false;
smtpServer.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpServer.Credentials = new System.Net.NetworkCredential("username", "passwd");
smtpServer.EnableSsl = true;

MailMessage msg = new MailMessage();
msg.To.Add("ToAddress");
msg.From = new MailAddress("FromAddress");
msg.Subject = "Test Mail";
msg.Body = "Test email from c#";

smtpServer.Send(msg);

It throws an exception:

Failure sending mail

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 173.194.66.108:587"}
System.Exception {System.Net.Sockets.SocketException}

I even tried changing port to 465 but didn't help. And also, I have turned off the security for Less secure app in configuration in gmail.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
atp9
  • 890
  • 1
  • 11
  • 23
  • are you using 2 factor authentication on your gmail account? – user1666620 Aug 02 '16 at 14:17
  • http://stackoverflow.com/questions/7102687/smtpclient-a-connection-attempt-failed-because-the-connected-party-did-not-prop – Oluwafemi Aug 02 '16 at 14:18
  • See following webpage : https://support.google.com/a/answer/176600?hl=en. SSL only works with port 465. Make sure the From Address matches the credentials(username). Also set default credentials to 'false'. – jdweng Aug 02 '16 at 14:18
  • @jdweng the OPs code already sets the `UseDefaultCredentials` property to false, and the OP already tried port 465. `EnableSsl` sets TLS as well, and port 587 is the TLS port. – user1666620 Aug 02 '16 at 14:21
  • @user1666620, 2 factor authentication is off for my account. – atp9 Aug 02 '16 at 14:27
  • @Oluwafemi, it was the question from where, I started looking for the solution but didn't help. I would suggest to try this code out if that works for your account. – atp9 Aug 02 '16 at 14:28
  • @atp_09 are you able to ping `smtp.gmail.com` from the machine you are running the code on? Is there a firewall running which could be blocking the application from sending the email? – user1666620 Aug 02 '16 at 14:32
  • @user1666620, here is the interesting thing, I am able to ping it but, when I observed the ip address in command prompt, it is 173.194.207.109. where as if you look at the ip in exception, its different. Is that default behavior ( I mean dynamic IPs) ? – atp9 Aug 02 '16 at 14:34
  • @atp_09 I wouldn't be too concerned about the specific IP address, but more the fact that you can connect to it. What about the ports? – user1666620 Aug 02 '16 at 14:38
  • @user1666620, port- TTL=43. – atp9 Aug 02 '16 at 14:39

0 Answers0