【问题标题】:Existing connection was forcibly closed by the remote host when sending mass email with attachement发送带有附件的大量电子邮件时,远程主机强制关闭现有连接
【发布时间】:2017-08-25 13:56:37
【问题描述】:

我有一种方法可以更新表中的行。它遍历受更改影响的所有公司客户,并通过电子邮件向所有应通知此更改的所有用户发送电子邮件,并附上可能的 pdf 文件。该文件保存在服务器上的特定位置。 这最终可能会从该方法调用发送 20 到 500 封电子邮件。

此方法由客户端调用一次,然后服务器完成所有工作。用于电子邮件的 PDF 文件永远不会更改,始终保持不变。

也许这种方法有更好的结构,或者我可以采取一些保护措施来避免服务器在运行该脚本时耗尽资源?

截至目前,出现以下错误:An existing connection was forcibly closed by the remote host System.Net.SocketsException: An existing connection was forcibly closed by the remote host 这是客服发给我的堆栈跟踪。

这里是该方法的大部分代码:

string attach = null;
string mergerFile = FileHelper.DirectoryName.MergerDocumentDirectory(instId) + mergerDocumentFileName;
        if (System.IO.File.Exists(mergerFile))
            attach = mergerFile;
string subject = "subject";
StringBuilder sbEmailBody = new StringBuilder();
sbEmailBody.Append("the email body etc...");

foreach(Company in companies){
    //do some business logic here
    foreach(User in Company.Users){
        CustomLibrary.Mail.SendEmail("from@mail.com", user.Email.Trim(), "", "", subject, true, emailBody, attach);
    }
}

CustomLibrary.Mail.SendEmail 方法

    SmtpClient smtpClient = new SmtpClient();
        MailMessage message = new MailMessage();

        smtpClient.Host = WebConfigurationManager.AppSettings["mailServer"];
        smtpClient.Port = 25;

        message.From = new MailAddress(EmailFrom);

        message.To.Add(EmailTo);
        message.Subject = EmailSubject;

         #region mail body

        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        //add some header, body and footer to the email body here

         #endregion

        // Message body content
        message.Body = sb.ToString();

        //Attachment
        message.Attachments.Clear();
        if (!String.IsNullOrEmpty(AttachmentFile))
        {
            Attachment myattach = new Attachment(AttachmentFile);
            message.Attachments.Add(myattach);
        }

        // Send SMTP mail
        smtpClient.Send(message);

【问题讨论】:

标签: c# email smtp


【解决方案1】:

您应该检查您的邮件服务器的日志。您可能超出了服务器设置的某些限制,这会导致它拒绝您的连接。

如果您无法控制邮件服务器,我建议您设置一个本地 SMTP 服务器(例如,IIS SMTP 服务非常简单且可靠)。您的代码在本地 SMTP 服务中假脱机,然后能够进行适当的重试、超时等。

【讨论】:

  • 我认为这是一个很好的起点,谢谢。我会看:)
猜你喜欢
  • 2014-12-02
  • 2023-03-26
  • 2010-11-12
  • 2011-11-04
  • 2023-03-31
  • 2019-01-14
  • 2011-01-06
  • 2013-08-08
  • 1970-01-01
相关资源
最近更新 更多