发送邮件异步不起作用

时间:2015-12-06 00:29:41

标签: c# asynchronous asp.net-mvc-5

  

我正在尝试发送电子邮件异步方法,但没有发送电子邮件

https://dotnetfiddle.net/oFVtN2

1 个答案:

答案 0 :(得分:2)

由于您的“火灾和遗忘”,您将立即处理邮件;这可能会影响你。此外,您没有处置邮件客户端。你应该把整个操作放到“火上浇油”中,包括创建和处理SmtpClient。更像是这样:

FireAndForgetTask(async cancellationToken =>
{
                using(var smtp = new SmtpClient
                {
                    Host = "myhost",
                    Port = 587,
                    EnableSsl = false,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    Credentials = new NetworkCredential("myemail", "mypass"),
                    Timeout = 50000
                })
                {          
                    using (var message = new MailMessage("myemail", destMail)
                    {
                        Subject = subject,
                        Body = mailBody,
                        IsBodyHtml = html           
                    })
                    {
                       await smtp.SendMailAsync(message);
                    }
                }
}