我最近切换到 ASP.NET MVC。当人们注册我的网站时,我想发送电子邮件确认。
因此,我取消注释 ASP.NET MVC 默认为此具有的代码并添加配置,web.config
但这不起作用,并且我一直遇到此错误:
SMTP 服务器需要安全连接或客户端未通过身份验证。服务器响应为:5.5.1 需要身份验证。
我创建了一个 asp.net webforms 并尝试从该项目发送电子邮件并且有效。因此,我复制了我在页面加载中用于在网络表单中发送电子邮件的代码,并将其放入帐户控制器中的注册操作中,但我再次遇到了该错误。
我真的不明白为什么在 ASP.NET MVC 中会出现此错误,但完全相同的代码在 webforms 中可以正常工作。
这是 ASP.NET MVC 注册操作中的代码:
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email, BirthDate=model.BirthDate };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
//string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
//var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
//await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("info@wwwebco.com"); //IMPORTANT: This must be same as your smtp authentication address.
mail.To.Add(user.Id);
//set the content
mail.Subject = "This is an email";
mail.Body = "This is from system.net.mail using C sharp with smtp authentication.";
//send the message
SmtpClient smtp = new SmtpClient("mail.wwwebco.com");
//IMPORANT: Your smtp login email MUST be same as your FROM address.
NetworkCredential Credentials = new NetworkCredential("info@wwwebco.com", "MyPassWord");
smtp.Credentials = Credentials;
await smtp.SendMailAsync(mail);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
我在 asp.net webforms 应用程序中的代码可以正常工作:
protected void Page_Load(object sender, EventArgs e)
{
//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("info@wwwebco.com"); //IMPORTANT: This must be same as your smtp authentication address.
mail.To.Add("armanhafezi@gmail.com");
//set the content
mail.Subject = "This is an email";
mail.Body = "This is from system.net.mail using C sharp with smtp authentication.";
//send the message
SmtpClient smtp = new SmtpClient("mail.wwwebco.com");
//IMPORANT: Your smtp login email MUST be same as your FROM address.
NetworkCredential Credentials = new NetworkCredential("info@wwwebco.com", "MyPassWord");
smtp.Credentials = Credentials;
smtp.Send(mail);
}
我真的被这个问题困住了。请帮忙!
谢谢你。