Why am I getting a connection timed out when trying to send an email through a CS program?

1.7k Views Asked by At

Firewall: Turned OFF. I am getting a connection timed out error. The email and password are verified.

The exception is: System.Net.Mail.SmtpException : The operation has timed out.

My code

 string filename = @"C:\emailsample.htm";

        string mailbody = System.IO.File.ReadAllText(filename);

        mailbody = mailbody.Replace("##NAME##", firstname.Text);

        string to = emailid.Text;

        string from = "[email protected]";

        MailMessage message = new MailMessage(from, to);

        message.Subject = "Auto Generated Mail";

        message.Body = mailbody;

        message.BodyEncoding = Encoding.UTF8;

        message.IsBodyHtml = true;

        SmtpClient client = new SmtpClient("smtp.gmail.com", 465);

        System.Net.NetworkCredential basic = new System.Net.NetworkCredential(from, "Password");

        client.EnableSsl = true;

        client.Timeout = 20000;

        client.DeliveryMethod = SmtpDeliveryMethod.Network;

        client.UseDefaultCredentials = false;

        client.Credentials = basic;

        try
        {
            client.Send(message);

        }

        catch (Exception ex)
        {
            System.Windows.MessageBox.Show(ex.ToString());
            return;
        }
1

There are 1 best solutions below

2
On

Try modifying the Port to 587.

Also verify if the From email is correct.

 SmtpClient client = new SmtpClient();
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("[email protected]","password");

MailMessage mm = new MailMessage("[email protected]", "[email protected]", "test", "test");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

client.Send(mm);