如何异步发送邮件

本文关键字:异步 何异步 | 更新日期: 2023-09-27 18:04:00

我在尝试发送异步电子邮件时遇到了一个问题,我发现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);
        }
    }
}

-未来的读者,处理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);
                    }
                }
            }
        }