Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SmtpClient - The operation has timed out

Tags:

c#

smtp

I am trying to create a small app using C# to send email, but I can't get it to work even using port 587 (GMail) TLS or 465 (GMail SSL). I'm not sure what is causing my problem, should I edit my app.config file? Here is my code:

try
{
  SmtpClient client = new SmtpClient("smtp.gmail.com", 465);
  client.EnableSsl = true;
  client.Timeout = 10000;
  client.DeliveryMethod = SmtpDeliveryMethod.Network;
  client.UseDefaultCredentials = false;
  client.Credentials = new NetworkCredential("myemailid", "mypwd");

  MailMessage msg = new MailMessage();
  msg.To.Add(txtTo.Text);
  msg.From = new MailAddress("myemailid");
  msg.Subject = txtSub.Text;
  msg.Body = txtMsg.Text;

  client.Send(msg);
  MessageBox.Show("sent");
}
catch (Exception ex) 
{
    MessageBox.Show(ex.Message);
}
like image 781
user3774291 Avatar asked Dec 20 '22 13:12

user3774291


1 Answers

Ports 25 & 465 caused problems. Changing port to 587 worked for me.

Dim myCredential As System.Net.NetworkCredential
myCredential = New System.Net.NetworkCredential("emailid", "pwd")
smtp.Host = "server"
smtp.Port = 587
smtp.EnableSsl = True
smtp.UseDefaultCredentials = False
smtp.Credentials = myCredential
smtp.Send(mm)
like image 136
Suresh Nair Avatar answered Dec 26 '22 16:12

Suresh Nair