C#中的电子邮件发送服务无法恢复

C#中的电子邮件发送服务无法恢复

本文介绍了服务器超时后,C#中的电子邮件发送服务无法恢复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几个月来我一直遇到这个问题,这让我发疯了。
我有一个用C#(.NET 4.5)编写的Windows服务,该服务基本上使用Outlook帐户发送电子邮件(我认为这是Office365服务)。我知道凭据顺序问题并没有影响我(许多电子邮件正确发送)。

I've been having this problem for months, and it's driving me nuts.I have a windows service written in C# (.NET 4.5) which basically sends emails, using an outlook account (I think it's an office365 service). I'm aware of the "order of credentials" problem, which isn't affecting me (many emails send correctly).

该服务正确启动并开始发送电子邮件。有时,当数量过多时,我会等待服务器出错,该服务会等待几分钟,然后自行继续正常运行。

The service starts correctly and begins sending emails. Sometimes when there's too many, I get a server error to wait, the service waits a few minutes and continues perfectly on its own.

在这些情况下,我得到错误A:

In these cases I get Error A:

 System.Net.Mail.SmtpException: The operation has timed out.
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at Cobranzas.WinService.Email.SendEmail(String subject, String body, String mailTo, String attPath)
   at Cobranzas.WinService.CobranzasEmailService.SendEmails(IEnumerable`1 toSend, RepositoryEf emailRepo)

问题:有时,我尚未找到一种模式,它每隔几天就会发生一次,它会发生超时错误,并且永远无法恢复(重新启动服务会立即对其进行修复)。所有后续发送尝试均失败,并出现相同的错误。在这种情况下,我混合了错误A和:

The problem: sometimes, and I haven't been able to find a pattern, it happens every few days, it gets a timeout error, and never recovers (restarting the services fixes it immediately). All subsequent sending tries fail with the same error. In this case, I get a mix of Error A and:

 System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: The operation has timed out.
   at System.Net.ConnectionPool.Get(Object owningObject, Int32 result, Boolean& continueLoop, WaitHandle[]& waitHandles)
   at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
   at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
   at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
   at System.Net.Mail.SmtpClient.GetConnection()
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   --- End of inner exception stack trace ---
   at System.Net.Mail.SmtpClient.Send(MailMessage message)
   at Cobranzas.WinService.Email.SendEmail(String subject, String body, String mailTo, String attPath)
   at Cobranzas.WinService.CobranzasEmailService.SendEmails(IEnumerable`1 toSend, RepositoryEf emailRepo)

我的服务逻辑如下:我有一个计时器,每5分钟进行一次迭代

The logic of my service is as follows: I have a timer which every 5 minutes iterates over a lot of emails to be sent, and for each executes

Thread.Sleep(2000);
try
{
    emailService.SendEmail(asunto, nuevoCuerpo, mail.Email, mail.AlertMessage.Attach);
}
catch (Exception ex)
{
    if (ex is System.Net.Mail.SmtpException)
    {
        Thread.Sleep(20000); // Lo hacemos esperar 20 segundos
    }
}

SendEmail方法为:

SendEmail method is:

var mailMessage = new MailMessage();

mailMessage.To.Add(mailTo);

mailMessage.Subject = subject;
mailMessage.Body = WebUtility.HtmlDecode(body);
mailMessage.IsBodyHtml = true;
mailMessage.From = new MailAddress(emailFromAddress, emailFromName);
mailMessage.Headers.Add("Content-type", "text/html; charset=iso-8859-1");

// Attachment
if (attPath != null)
{
    var data = new Attachment(attPath, MediaTypeNames.Application.Octet);
    mailMessage.Attachments.Add(data);
}

var cred =
    new NetworkCredential(emailFromAddress, emailFromPassword);

using (var mailClient =
    new SmtpClient(emailSmtpClient, emailSmtpPort)
                     {
                         EnableSsl = true,
                         DeliveryMethod = SmtpDeliveryMethod.Network,
                         UseDefaultCredentials = false,
                         Timeout = 20000,
                         Credentials = cred
                     })
{
    mailClient.Send(mailMessage);
}

foreach (Attachment attachment in mailMessage.Attachments)
{
    attachment.Dispose();
}

使用SmtpClient和附件处理是新的,我们添加了它们来修复这个。没有行为变化。
Thread.sleep代码之后,超时被新的和未经考验的呢。

The using SmtpClient, and attachment disposing are new, we added them trying to fix this. There was no behaviour change.T̶h̶e̶ ̶T̶h̶r̶e̶a̶d̶.̶S̶l̶e̶e̶p̶ ̶a̶f̶t̶e̶r̶ ̶t̶h̶e̶ ̶t̶i̶m̶e̶o̶u̶t̶ ̶i̶s̶ ̶n̶e̶w̶ ̶a̶n̶d̶ ̶u̶n̶t̶e̶s̶t̶e̶d̶ ̶y̶e̶t̶.

由于重新启动它,我怀疑的东西修复服务不关闭/清洗适当地,但是我检查了一下,找不到可能的情况。我发现链接前有一段时间,但是它

Given that restarting the service fixes it, I'm suspecting something not being closed/cleaned appropriately, but I've checked and can't find what it could be. I found this link a while ago, but it looks pretty old.

任何帮助深表感谢!

[进展]

我已经测试了20超时后的等待,但没有任何结果,它仍然以相同的方式失败。有什么想法吗?我们对此感到很困惑。 p>

I've tested the 20" wait after a timeout and nothing, it's still failing in the same way. Any ideas? We're really stumped with this.

推荐答案

我遇到了完全相同的问题。在这里找到了解决方案:

I have the exact same problem. I found the solution here:

System.Net.WebException发出两个以上并发的WebRequests

System.Net.WebException when issuing more than two concurrent WebRequestshttp://www.wadewegner.com/2007/08/systemnetwebexception-when-issuing-more-than-two-concurrent-webrequests/

基本上,我更改了并发到单个外部服务器的最大连接数。到那个文档,它是2。尽管它有一个超时(它等待一段时间,直到一个被释放然后继续),但有时还不够,它会挂起。

Basically, I changed the max number of connections allowed concurrently to a single external server. By default, according to that documentation it was 2. Although, it has a timeout (it waits sometime until one is released and then continues), at sometimes, it is not enough and it hangs.

<configuration>
    <system.net>
        <connectionManagement>
        <add address="*" maxconnection="100" />
        </connectionManagement>
    </system.net>
</configuration>

我无法找到第一次超时后如何恢复的方法,但希望这样可以解决超时错误会持续一段时间。

I have not been able to find out how to recover after first timeout but hopefully this would get out "timeout" errors out of the way for some time.

这篇关于服务器超时后,C#中的电子邮件发送服务无法恢复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 01:49