尝试通过CS程序发送电子邮件时,为什么我的连接超时?

时间:2014-11-14 11:56:35

标签: c# .net smtp gmail smtpclient

防火墙:关闭。我收到连接超时错误。电子邮件和密码已经过验证。

例外是:System.Net.Mail.SmtpException:操作已超时。

我的代码

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

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

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

        string to = emailid.Text;

        string from = "xxx.abc45@gmail.com";

        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 个答案:

答案 0 :(得分:0)

尝试将端口修改为587。

同时验证发件人电子邮件是否正确。

 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("user@gmail.com","password");

MailMessage mm = new MailMessage("donotreply@domain.com", "sendtomyemail@domain.co.uk", "test", "test");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

client.Send(mm);