首页 > 解决方案 > 发送 SMTP 电子邮件在控制台应用程序中被强制关闭,然后才能在 .NET 中发送电子邮件

问题描述

我有一个发送电子邮件的电子邮件通知程序应用程序,我们在每 5 分钟运行一次的控制台应用程序中执行此操作。我们在任务中运行电子邮件部分,以便它可以继续处理另一组通知。

但是,我们运行一个通知,控制台关闭并且电子邮件永远不会发送。在 SMTP 方面,它说主机被强制关闭。我怎样才能让控制台应用程序保持活动状态,直到所有任务都完成,但仍然能够多线程。

读取操作失败。传输的字节数:0 远程 IP:44.444.444.44,会话:124992,代码:10054,消息:远程主机强制关闭现有连接

private Task SendFromServer(MailMessage mailMessage, bool reuse, bool useServerSmtp)
{
    return Task.Factory.StartNew(() =>
                {
                    var smtp = new SmtpClient();
                    smtp.Send(mailMessage);
                }
                catch (Exception ex)
                {
                    Logger.Error(ex.InnerException ?? ex);
                }
                finally
                {
                    if(!reuse)
                        mailMessage.Dispose();
                }
            });
        }
}

标签: c#.netmultithreadingtask-parallel-libraryconsole-application

解决方案


使用SmtpClient.SendMailAsync可以等待的。

private async Task SendFromServer(MailMessage mailMessage) {
    using (var smtp = new SmtpClient()) {
        try {
            await smtp.SendMailAsync(mailMessage);
        } catch (Exception ex) {
            Logger.Error(ex.InnerException ?? ex);
        }
    }
}

并且由于它是在控制台应用程序中调用的,因此您需要像这样调用它

//get all notification tasks. Assuming notifications => List<MailMessage>
var tasks = notifications.Select(message => SendFromServer(message));
//execute all asynchronously
Task.WhenAll(tasks).GetAwaiter().GetResult();

所以控制台应用程序等待他们所有人完成他们的任务


推荐阅读