SmtpClient.Send 将发送一条消息并超时
我正在更新一些旧代码以与 SQL 集成。我在一家公司工作,该公司偶尔会发送大量电子邮件,这会极大地降低邮件服务器的速度。如果电子邮件开始堆积,我们希望将其排队到数据库中。在测试代码的一些更改时,我注意到我会收到电子邮件,但客户端仍然会超时。这会导致问题,因为客户端随后会将电子邮件设置在队列中,并且稍后当另一个服务尝试清理数据库时我会收到它。
SmtpClient emailClient = new SmtpClient(Settings.SmtpServer);
emailClient.Timeout = 100;
bool sent = false;
try
{
using (Impersonate imp = DA.GetImpersonator())
{
emailClient.Send(message);
sent = true;
}
}
catch (SmtpException) { }
finally
{
if (sent)
{
email.IsSent = true;
DA.Save(email);
}
}
10次测试运行,9次超时,1次成功;我收到了 7 封电子邮件。
I am updating some older code to be integrated with SQL. I work for a company that occasionally sends out bulk emails that slows down the mail server immensely. We want to queue the emails into the database if they start building up. While testing some changes to the code, I noticed that I would receive the email and the client would still timeout. This would cause problems as the client would then set the email in the queue and I would receive it later when another service attempts to clean out the database.
SmtpClient emailClient = new SmtpClient(Settings.SmtpServer);
emailClient.Timeout = 100;
bool sent = false;
try
{
using (Impersonate imp = DA.GetImpersonator())
{
emailClient.Send(message);
sent = true;
}
}
catch (SmtpException) { }
finally
{
if (sent)
{
email.IsSent = true;
DA.Save(email);
}
}
Out of 10 test runs, 9 timed out, 1 succeeded; I received 7 emails.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从规范来看,超时仅承诺该方法将在该时间内返回,而不是发送已停止。
如果您需要发送多封电子邮件,请考虑使用SendAsync 方法并订阅到 SendCompleted 事件来确定发送电子邮件的成功/失败。
From looking at the spec, the timeout only promises that the method will return within that time, not that the sending has been stopped.
If you need to send multiple emails, consider using the SendAsync method and subscribe to the SendCompleted event to determine the success / failure of sending the email.