c# - 发送 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();
}
});
}
}
解决方案
使用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();
所以控制台应用程序等待他们所有人完成他们的任务
推荐阅读
- c# - 如何在 Linux 上的 .net 核心中获取系统规格
- mysql - Wordpress php_network_getaddresses: getaddrinfo failed: Temporary failure ,但其他与 mysql 连接的尝试工作正常
- java - AsyncTask 在调试时杀死 istelf 而没有任何错误消息
- php - 在调度器中调度 Laravel 作业,pre-5.5
- r - 对于两个大小相等的向量,如何在每个索引处创建一个包含任一向量的最大值(或最小值)的新向量?
- php - Codeigniter $this->db->field_data 跨多个模式获取字段的问题
- git - 从脚本执行 git 提交
- ios - 为什么 CHECK_INCLUDE_FILE 在 ios.cmake 更改后不起作用?
- php - 无效的日期时间格式:1366 不正确的整数值:
- pandas - 根据其他列值估算值