发送 SMTP 电子邮件在控制台应用程序中被强行关闭,然后才能在 .NET 中发送电子邮件
Send SMTP email getting forcibly closed in console application before it can send email in .NET
我有一个发送电子邮件的电子邮件通知应用程序,我们在控制台应用程序中发送电子邮件,运行每 5 分钟发送一次。我们 运行 任务中的电子邮件部分,因此它可以继续处理另一组通知。
但是,我们 运行 一个通知,控制台关闭并且电子邮件永远不会发送。在 SMTP 端,它表示主机已被强制关闭。我怎样才能让控制台应用程序保持活动状态直到所有任务完成,但仍然能够多线程。
The read operation failed. Bytes transferred: 0 Remote IP:
44.444.444.44, Session: 124992, Code: 10054, Message: An existing connection was forcibly closed by the remote host
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();
因此控制台应用程序等待所有这些人完成任务
我有一个发送电子邮件的电子邮件通知应用程序,我们在控制台应用程序中发送电子邮件,运行每 5 分钟发送一次。我们 运行 任务中的电子邮件部分,因此它可以继续处理另一组通知。
但是,我们 运行 一个通知,控制台关闭并且电子邮件永远不会发送。在 SMTP 端,它表示主机已被强制关闭。我怎样才能让控制台应用程序保持活动状态直到所有任务完成,但仍然能够多线程。
The read operation failed. Bytes transferred: 0 Remote IP: 44.444.444.44, Session: 124992, Code: 10054, Message: An existing connection was forcibly closed by the remote host
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();
因此控制台应用程序等待所有这些人完成任务