Asp.Net Identity 2.0 - 如何使用SmtpClient实现IIdentityMessageService来执行异步SMTP?

时间:2014-04-01 22:06:53

标签: c# asp.net-identity smtpclient

我已经为Asp.Net Identity 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);
        }
    }
}

要发送电子邮件,我会通过UserManager:

await _userManager.SendEmailAsync(user.Id, "Confirm your account","Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");

问题在于,当我致电System.Threading.Tasks.TaskCanceledException时,我收到了SendEmailAsync(),而且不清楚原因。

如果我同步发送电子邮件(client.Send(email)),一切正常。

所以我的问题是:

  • 如何防止抛出TaskCanceledException? (假设我能克服这个错误),

  • 我应该如何在电子邮件发送回客户端时传达错误(例如,&#34;此处没有此类用户&#34;从SmtpClient输入回复?

2 个答案:

答案 0 :(得分:30)

您的问题是在发送电子邮件之前处理了SmtpClient

两种方式:

  • 等待SendMailAsync结果

    using (var client = new SmtpClient())
    {
        await client.SendMailAsync(email);
    }
    
  • 注册SendCompleted事件并仅在发送邮件后处理SmtpClient

    var client = new SmtpClient();
    client.SendCompleted += (s, e) => {
        client.Dispose();
    };
    return client.SendMailAsync(message);
    

答案 1 :(得分:6)

您必须在方法上设置异步。

    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);
                }
            }
        }
    }