这是我在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 = "akanksha16296@gmail.com";
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文件中没有配置任何内容。我在这两个类中简单地对所有内容进行了硬编码。
我已根据SSL的SendGrid文档中的建议将端口号从527更改为465。 现在,我得到以下错误--- 异常详细信息: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
答案 0 :(得分:0)
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/