【问题标题】:Why am I getting a connection timed out when trying to send an email through a CS program?为什么我在尝试通过 CS 程序发送电子邮件时连接超时?
【发布时间】:2015-01-11 19:34:33
【问题描述】:

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

异常是: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;
        }

【问题讨论】:

  • 你能完整发布异常吗?
  • Message : 操作已超时。
    StackTrace : 在 System.Net.Mail.SmtpClient.Send(MailMessage message) at WpfApplication1.EmailReg.SendEmail() in C:(Path here )\EmailReg.xaml.cs:149 行

标签: c# .net smtp gmail smtpclient


【解决方案1】:

尝试将端口修改为 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);

【讨论】:

  • 我查过了。这看起来不错的样子。同样早些时候它是 587,但它给出了安全身份验证错误,所以我将其更改为 465,之后它开始给我超时错误。
  • 我认为您需要提供 NetworkCredentials 请参阅我在上面的答案中编辑的这段代码
猜你喜欢
  • 2015-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-15
  • 2022-08-03
  • 1970-01-01
相关资源
最近更新 更多