System.Net.Mail.SmtpException:SMTP命令超时 - 关闭连接

时间:2012-05-15 18:41:04

标签: c# email structuremap smtpclient system.net.mail

我偶尔会发生错误。当我遇到此错误时,如果我再试一次,电子邮件将发送。我无法可靠地重现错误,但它经常受到影响。

  

System.Net.Mail.SmtpException:服务不可用,关闭传输通道。服务器响应为:[Servername]:SMTP命令超时 - 关闭连接

堆栈追踪:

  System.Net.Mail.SmtpTransport上System.Net.Mail.MailCommand.Send(SmtpConnection conn,Byte []命令,String from)的System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode,String response)上的

System.Net.Mail.SmtpClient.Send(MailMessage消息)中的.SendMail(MailAddress发件人,MailAddressCollection收件人,String deliveryNotify,SmtpFailedRecipientException& exception)

这是有问题的代码。它使用HTML模板(使用Web url默认备份驱动的数据库)来注入值并创建html电子邮件。

public void AccountActivationEmail(Common.Request.Email.AccountActivation request)
{
    var profile = profileRepository.GetOne(new ProfileByUsername(request.Username, request.SiteId));
    var options = siteService.GetOptions(new GatewayOptionsRequest()
    {
        SiteId = request.SiteId
    });
    var site = options.Site;

    ExpiringHMAC hmac = new ExpiringHMAC(request.ExpireOn, new string[] { request.AccountId.ToString(), request.AccountKey.ToString(), request.Username });

    Dictionary<string, string> data = new Dictionary<string, string>();

    data.Add("{{logourl}}", String.IsNullOrEmpty(options.FullyHostedGateway.LogoUrl) ? UrlHelper.ConvertRelativeToAbsolute("/content/images/spacer.png") : options.FullyHostedGateway.LogoUrl);
    data.Add("{{name}}", profile.Name.DisplayName);
    data.Add("{{sitename}}", site.Name.DisplayName);
    data.Add("{{activationlink}}", String.Format(ActivationUrlFormat, options.UrlFriendlyName, Encryption.EncryptQueryString(request.Username), hmac.ToString()));

    MailDefinition template = new MailDefinition();
    MailMessage message = null;
    var emailTemplate = options.GetEmailTemplate(EmailTemplateType.ActivateAccount);
    string defaultSubject = "Activate Account";

    bool hasTemplate = false;

    if (emailTemplate != null)
    {
        hasTemplate = !String.IsNullOrEmpty(emailTemplate.Template);
    }

    if (!hasTemplate)
    {
        template.BodyFileName = activationDefaultTemplateUrl;
        message = template.CreateMailMessage(request.EmailAddress, data, new System.Web.UI.LiteralControl());
        message.IsBodyHtml = true;
        message.Subject = defaultSubject;
    }
    else
    {
        message = template.CreateMailMessage(request.EmailAddress, data, emailTemplate.Template, new System.Web.UI.LiteralControl());
        message.IsBodyHtml = emailTemplate.IsHtml;

        if (!String.IsNullOrEmpty(emailTemplate.Subject))
            message.Subject = emailTemplate.Subject;
        else
            message.Subject = defaultSubject;
    }

    if (options.ContactDetails != null)
    {
        if (!String.IsNullOrEmpty(options.ContactDetails.EmailAddress))
            message.From = new MailAddress(options.ContactDetails.EmailAddress);
    }

    SmtpClient client = new SmtpClient();

    client.Send(message);
}

此代码是使用Structuremap作为单例生成的类的一部分。我想也许这可能会导致问题,但每次调用该方法时,都会创建一个新的SmtpClient对象,这可以消除我在使用相同的连接发送多封电子邮件时遇到的问题。

我们没有阻止或限制连接,这是我们的电子邮件托管正在采取的官方立场。我想看看有没有办法做得更好,所以我没有得到这些错误。

修改

我的web.config中定义了我的邮件服务器。我已经通过我的电子邮件托管确认我的设置是正确的。

  <system.net>
      <mailSettings>
        <smtp deliveryMethod="Network" from="no-reply@mydomain.com">
          <network host="smtp.emailhost.com" userName="someaddress@mydomain.com" 
              password="myPassword1" port="2500" />
        </smtp>
      </mailSettings>
  </system.net>

1 个答案:

答案 0 :(得分:2)

发送后是否丢弃了Smtp Client对象?从http://connect.microsoft.com/VisualStudio/feedback/details/337557/smtpclient-does-not-close-session-after-sending-message看起来“......即使你每次都在创建一个新的SmtpClient实例,它仍然使用相同的通用会话。”

所以也许

using (SmtpClient client = new SmtpClient())
{
    client.Send(message);
}