如何发送邮件异步

时间:2014-05-18 19:12:44

标签: 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.

有什么建议吗?

2 个答案:

答案 0 :(得分:14)

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

答案 1 :(得分:0)

- 未来读者,处理MailMessage,或者我更喜欢使用using语法!我不知道当你不处理它或者它能以某种方式被回收时你会失去多少记忆。我将向用户发送大量电子邮件,因此我不想知道如果单独留下它是否会停止工作。

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

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