SMTP服务器需要安全连接,或者客户端未通过身份验证--连接超时

本文关键字:连接 身份验证 超时 客户端 或者 服务器 安全 SMTP | 更新日期: 2023-09-27 18:20:51

这个问题已经被问了&我试过每一个&我在堆栈溢出中发现的每一件事我都把头撞到墙上,不确定我到底在哪里犯了错误,无论如何,这是我的代码。

using (MailMessage mm = new MailMessage("sender@gmail.com", txtEmail.Text))
{
    mm.Subject = "Account Activation";
    string body = "Hello " + txtUsername.Text.Trim() + ",";
    body += "<br /><br />Please click the following link to activate your account";
    body += "<br /><a href = '" + Request.Url.AbsoluteUri.Replace("CS.aspx", "CS_Activation.aspx?ActivationCode=" + activationCode) + "'>Click here to activate your account.</a>";
    body += "<br /><br />Thanks";
    mm.Body = body;
    mm.IsBodyHtml = true;
    SmtpClient smtp = new SmtpClient();
    smtp.Host = "smtp.gmail.com";
    smtp.Port = 587;
    smtp.EnableSsl = true;
    smtp.UseDefaultCredentials = false;
    NetworkCredential NetworkCred = new NetworkCredential("sender@gmail.com", "password");
    smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
    smtp.Credentials = NetworkCred;
    smtp.Send(mm);
}

我曾尝试将默认凭据更改为false,但我注意到,当我将端口号从587更改为465时,连接超时。

SMTP服务器需要安全连接,或者客户端未通过身份验证--连接超时

我认为您可能过于复杂了。您不应该使用NetworkCredential。应该是这样的:

using (MailMessage mm = new MailMessage("sender@gmail.com", txtEmail.Text))
{
    mm.Subject = "Account Activation";
    string body = "Hello " + txtUsername.Text.Trim() + ",";
    body += "<br /><br />Please click the following link to activate your account";
    body += "<br /><a href = '" + Request.Url.AbsoluteUri.Replace("CS.aspx", "CS_Activation.aspx?ActivationCode=" + activationCode) + "'>Click here to activate your account.</a>";
    body += "<br /><br />Thanks";
    mm.Body = body;
    mm.IsBodyHtml = true;
    SmtpClient smtp = new SmtpClient();
    smtp.Host = "smtp.gmail.com";
    smtp.Port = 465;
    smtp.ConnectType = SmtpConnectType.ConnectSSLAuto;
    smtp.User = "gmailid@gmail.com";
    smtp.Password = "yourpassword";
    smtp.Send(mm);
}
相关文章: