我们已经实施了自己的定制批量电子邮件软件。三年来,我们将它与本地Exchange服务器一起使用,从未遇到任何问题。几个月前,我们切换到Office 365,现在遇到的问题是,电子邮件发送突然停止。
我复制了下面代码的草图。我们使用System.Net.Mail中的SmtpClient.SendMailAsync。由于我们需要能够限制每分钟的电子邮件数量,因此我们在每次成功发送电子邮件后启用了一个计时器,并触发下一封电子邮件。在随机时间,该过程停止,标记为***的行的日志输出。所以看起来好像SendMailAsync永远不会返回,而且之后的行永远不会被执行。没有错误信息,没有。不过,程序本身看起来并没有崩溃或陷入僵局。
知道我们的代码是否有问题? 怎么可能SendMailAsync永远不会返回?
private async Task SendEmailAsync(Recipient recipient)
{
MailMessage mm = new MailMessage();
...
System.Net.NetworkCredential creds = new System.Net.NetworkCredential();
...
using (SmtpClient sc = new SmtpClient(Host, Port))
{
sc.EnableSsl = UseSSL;
sc.UseDefaultCredentials = false;
sc.Credentials = creds;
mm.Body = ...
mm.To.Add(recipient.Adress);
progressViewModel.Log($"Sending e-mail to: {recipient.Adress} ..."); ***
await sc.SendMailAsync(mm);
progressViewModel.Log($"... Sent e-mail to: {recipient.Adress}");
}
}
private async void StartNextEmail()
{
try
{
timer.IsEnabled = false;
//check aborted or completed
...
Recipient currentRecipient = ...
await SendEmailAsync(currentRecipient);
timer.IsEnabled = true;
}
catch (SmtpException ex)
{
//failed, implement retry logic
...
timer.IsEnabled = true;
}
catch (Exception ex)
{
//unexpected error, abort
...
}
}
private void timer_Tick(object sender, EventArgs e)
{
StartNextEmail();
}