【问题标题】:Understanding how SmtpClient handles retries了解 SmtpClient 如何处理重试
【发布时间】:2011-04-14 16:25:40
【问题描述】:

我正在使用 GoogleApps 帐户从我的 (mvc) 网络应用发送事件通知。通常一切正常。当系统被要求发送超过 75 条消息时,我看到了来自 SMTP 服务器的回复:

服务不可用,正在关闭 传输通道。服务器 响应是:4.7.0 稍后再试, 关闭连接。 (邮件) uf10sm1153163icb.17

但是,系统正在自动重试,并且最终要求我的系统发送的任何内容(据我目前所知的一切)都会将其发送出去。但考虑到代码如何生成和发送电子邮件,我不明白这些重试是如何处理的。

我想尝试减慢传输速度,希望如果提交异步发生,导致“服务不可用”情况的任何原因都会得到安抚。但从代码的外观来看,它已经是因为我使用的是 Try |捕获块。

这是我的门面代码的相关部分:

foreach (string email in recipientEmails)
{
    try
    {
        EmailGateway.Instance.SendEmail(email, notificationSubject, notificationMessage);
   }
    catch (Exception ex)
    {
        Logger.Instance.LogException(ex);
        Logger.Instance.LogMessage("ERROR! Unsent email is to: " + email );
    }
    Logger.Instance.LogMessage("Sent " + notificationSubject + " to " + email);
}

这是网关代码(使用 System.Net.Mail;):

public virtual void SendEmail(string replyToAddress, string toEmailAddress, string subject, string body)
{
    string destinationEmailAddress = toEmailAddress;
    string fromEmailAddress = "my@address.com";
    bool useSSL = "true";

    MailMessage message = new MailMessage(fromEmailAddress, destinationEmailAddress, subject, body);
    message.IsBodyHtml = true;

    SmtpClient smtp = new SmtpClient();
    smtp.EnableSsl = useSSL;

    smtp.Send(message);
}

所以我将成功和失败都记录到我的记录器表中。我不明白的是,我如何才能看到 both 失败的日志消息,然后是同一电子邮件地址的成功条件。这表示“重试”,虽然我对 SmtpClient(本机 .net 程序集)可以在没有明确代码要求的情况下重试并不感到惊讶,但我看不出我的外观代码是如何记录这两种情况的。

【问题讨论】:

    标签: asp.net gmail smtpclient


    【解决方案1】:

    SmtpClient 未重试发送电子邮件。
    在您的外观代码中,无论您是否遇到异常,您总是会记录成功。
    您应该在 try 块中记录成功,否则您将捕获异常(记录失败),从 catch 块中出来并记录成功,这就是您所观察到的。

    foreach (string email in recipientEmails)
    {
        try
        {
            EmailGateway.Instance.SendEmail(email, notificationSubject, notificationMessage);
            Logger.Instance.LogMessage("Sent " + notificationSubject + " to " + email);
    
       }
        catch (Exception ex)
        {
            Logger.Instance.LogException(ex);
            Logger.Instance.LogMessage("ERROR! Unsent email is to: " + email );
        }
    } 
    

    【讨论】:

      猜你喜欢
      • 2011-02-16
      • 1970-01-01
      • 1970-01-01
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      • 2016-04-25
      • 2017-11-16
      • 2019-03-01
      相关资源
      最近更新 更多