gpt4 book ai didi

c# - 如何发送邮件异步

转载 作者:太空狗 更新时间:2023-10-30 00:04:56 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com