[英]Asp.Net Identity 2.0 - How to Implement IIdentityMessageService to do Async SMTP using SmtpClient?
I've implemented a simple EmailService for Asp.Net Identity 2.0 (via the IIdentityMessageService
interface. 我实现了Asp.Net 2.0身份简单EmailService(通过IIdentityMessageService
接口。
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
// convert IdentityMessage to a MailMessage
var email =
new MailMessage(new MailAddress("noreply@mydomain.com", "(do not reply)"),
new MailAddress(message.Destination))
{
Subject = message.Subject,
Body = message.Body,
IsBodyHtml = true
};
using (var client = new SmtpClient()) // SmtpClient configuration comes from config file
{
return client.SendMailAsync(email);
}
}
}
To send an email, I go through UserManager: 要发送电子邮件,我将通过UserManager:
await _userManager.SendEmailAsync(user.Id, "Confirm your account","Please confirm your account by clicking this link: <a href=\\"" + callbackUrl + "\\">link</a>");
The problem is that I get a System.Threading.Tasks.TaskCanceledException
when I call SendEmailAsync()
and it's not clear why. 问题是,当我调用SendEmailAsync()
时,我得到一个System.Threading.Tasks.TaskCanceledException
,并且不清楚为什么。
If I send email synchronously ( client.Send(email)
), everything works fine. 如果我同步发送电子邮件( client.Send(email)
),一切正常。
So my questions are: 所以我的问题是:
How do I prevent the TaskCanceledException from getting thrown? 如何防止TaskCanceledException被抛出? and (assuming I can overcome this error), (假设我能克服这个错误),
How should I go about communicating errors during email sending back to the client (ie, "no such user here" type responses from the SmtpClient? 我应该如何在电子邮件发送回客户端时传达错误(即“此处没有此类用户”类型的响应来自SmtpClient?
Your problem is that SmtpClient
is disposed before the email is sent. 您的问题是在发送电子邮件之前处理了SmtpClient
。
Two ways: 两种方式:
Await the SendMailAsync
result 等待SendMailAsync
结果
using (var client = new SmtpClient()) { await client.SendMailAsync(email); }
Register the SendCompleted
event and dispose the SmtpClient
only after the message is sent 注册SendCompleted
事件并仅在发送消息后处置SmtpClient
var client = new SmtpClient(); client.SendCompleted += (s, e) => { client.Dispose(); }; return client.SendMailAsync(message);
You must put async on method. 您必须在方法上放置异步。
public async Task SendAsync(IdentityMessage message)
{
using (SmtpClient client = new SmtpClient())
{
using (var mailMessage = new MailMessage("your@email.com", message.Destination, message.Subject, message.Body))
{
await client.SendMailAsync(mailMessage);
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.