这是我在IdentityConfig.cs文件中的简单EmailService类。
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// Plug in your email service here to send an email.
// return Task.FromResult(0);
const string userName = "ashish_qluto";
const string from = "[email protected]";
const string password = "xxxxxx";
//const int port = 587;
var smtpClient = new SmtpClient("smtp.sendgrid.net", Convert.ToInt32(587));
smtpClient.Port = 587;
// smtpClient.ServicePoint.MaxIdleTime = 1;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
// smtpClient.Credentials = new NetworkCredential(userName, password);
NetworkCredential credentials = new NetworkCredential(userName, password);
smtpClient.EnableSsl = true;
smtpClient.Credentials = credentials;
var mailMessage = new MailMessage(from, message.Destination);
mailMessage.Subject = message.Subject;
mailMessage.Body = message.Body;
return smtpClient.SendMailAsync(mailMessage);
}
}
这是我的Register方法的POST版本,在成功注册后,我尝试在其中发送电子邮件链接。
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var 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 this link:");
//ViewBag.Link = callbackUrl;
return View("CheckYourEmail");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
我看过许多有关邮件发送的文章。我的web.config文件中未配置任何内容。我只是将这两个类中的所有内容都硬编码了。
我已将端口号从527更改为465,如SSL的SendGrid文档中所建议。现在,我收到以下错误消息-异常详细信息:System.Net.Mail.SmtpException:语法错误,无法识别命令。服务器响应为:并且导致错误的行是---
var callbackUrl = Url.Action("ConfirmEmail","Account",new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
/// this function SendEmailAsync is causing Syntax error
await UserManager.SendEmailAsync(user.Id,"Confirm your account","Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
return View("CheckYourEmail");
整个堆栈跟踪在这里--- http://pastebin.com/yMiZaS9Q
const string userName = "ashish_qluto";
需要。。
const string userName = "apikey";
对于密码...
const string password = "xxxxxx"; // xxxxxx = sendgrid api key
请参阅sendgrid smpt文档以获取更多详细信息。
https://sendgrid.com/docs/for-developers/sending-email/getting-started-smtp/