我找到了很多关于这个问题的答案,但仍无法解决我的问题。我正在使用此代码向用户发送帐户激活邮件。但我收到此错误“SMTP服务器需要安全连接或客户端未经过身份验证。服务器响应为:5.5.1需要身份验证。”
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.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential("sender@gmail.com", "<password>");
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
//var client = new SmtpClient("smtp.gmail.com", 587)
//{
// Credentials = new NetworkCredential("myusername@gmail.com", "mypwd"),
// EnableSsl = true
//};
//client.Send("myusername@gmail.com", "myusername@gmail.com", "test", "testbody");
}
答案 0 :(得分:0)
问题就像水,代码从上到下执行。您正在传递凭据,但同时将UseDefaultCredentials设置为true。这导致了这个问题。大多数服务器都需要身份验证,例如EnableSsl和凭据(用户名/密码组合),以便从其服务器发送电子邮件。
因此,解决方案是删除以下行,
smtp.UseDefaultCredentials = true;
然后代码将执行,电子邮件将被发送。