c# - 如何发送邮件异步

标签 c# .net identity

我在尝试发送电子邮件异步时遇到了问题,我发现 Stackoverflow 上没有帖子,但没有一个有用。我有以下代码块

public class EmailService : IIdentityMessageService
{
    public Task SendAsync(IdentityMessage message)
    {
        // Plug in your email service here to send an email.

        var mailMessage = new MailMessage
            ("me@example.com", message.Destination, message.Subject, message.Body);

        mailMessage.IsBodyHtml = true;

        var client = new SmtpClient();

        client.SendCompleted += (s, e) => client.Dispose();
        client.SendAsync(mailMessage,null);
        return Task.FromResult(0);
    }
}

我收到一封电子邮件,但在运行这段代码时出现异常

an asynchronous module or handler completed while an asynchronous operation was still pending.

有什么建议吗?

最佳答案

使用SendMailAsync而不是 SendAsync:

public class EmailService : IIdentityMessageService
{
    public async Task SendAsync(IdentityMessage message)
    {
        // Plug in your email service here to send an email.

        var mailMessage = new MailMessage
            ("me@example.com", message.Destination, message.Subject, message.Body);

        mailMessage.IsBodyHtml = true;

        using(var client = new SmtpClient())
        {
            await client.SendMailAsync(mailMessage);
        }
    }
}

关于c# - 如何发送邮件异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23725829/

相关文章:

.net - 使用 jQuery 将 JSON 对象发送到 asp.net WebMethod 时出错

c# - Windows Azure 连接到 MySQL DB 中的 InvalidCastException

zend-framework2 - ZfcRbac 角色提供者和身份 getRoles()

c# - 调用 Facebook/Google+ 时 ExternalLogin 未命中

c# - 为什么我的未经授权的 Controller 不返回 401 ASP.Net Core?

c# - 为什么有时在计时器滴答事件中它会连续调用该方法两次?

c# - 无法访问的代码和验证

c# - 使用 rackspace 托管负载均衡器后面的自托管 Web API 获取客户端 IP

.net - CruiseControl.NET,Nant 真的有必要吗?

sql - 类似身份的列,但基于分组条件