【发布时间】:2017-01-17 03:19:39
【问题描述】:
我正在尝试使用 SmtpClient.SendMailAsync 发送一封电子邮件,但它不起作用,尽管同步版本有效 (SmtpClient.Send)。
我的同步代码:
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress("someEmail@gmail.com", "SomeOne"));
msg.From = new MailAddress("no-reply@group.com", "You2");
msg.Subject = "This is a Test Mail";
msg.Body = "This is a test message";
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = true;
client.Port = 25;
client.Host = "mail.group.com";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Send(msg);
我的异步电子邮件代码(我刚刚修改了 EmailService : IIdentityMessageService 类):
public Task SendAsync(IdentityMessage message)
{
const string sentFrom = "support@group.com";
// Configure the client:
var client = new SmtpClient("mail.group.com")
{
Port = 25,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = true,
EnableSsl = true
};
// Create the message:
var mail = new MailMessage(sentFrom, message.Destination, message.Subject, message.Body);
// Send:
return client.SendMailAsync(mail);
}
编辑:调用代码由Visual Studio生成,这里是:
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)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// 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, "Confirmer votre compte", "S'il vous plaît, cliquez le lien suivant : <a href=\"" + callbackUrl + "\">Activation</a>");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
【问题讨论】:
-
为什么不生火然后忘记呢?只需将方法更改为
async void并在client.SendMailAsync(mail)中调用 await -
因为在MVC生成的代码中已经是这样了。好名字:-)
-
@MusicAndCode 谢谢:)
标签: c# asynchronous smtp