我有类似的情况,我正在发送多封电子邮件,而不是等待一封完成后再发送另一封。
我所做的是为要发送的每封邮件启动一个新的 SMTPClient 并异步发送。像这样:
private void SendMailAsync(string ids, MailMessage mail)
{
SmtpClient client = null;
try
{
client = new SmtpClient(ConfigurationManager.AppSettings["MailServer"], Convert.ToInt32(ConfigurationManager.AppSettings["MailPort"]));
string userState = "MailQueueID_" + ids;
client.SendCompleted += (sender, e) =>
{
// Get the unique identifier for this asynchronous operation
String token = (string)e.UserState;
DateTime now = DateTime.Now;
try
{
if (e.Cancelled)
{
LogError(new Exception(token + " - Callback cancelled"));
return;
}
if (e.Error != null)
{
LogError(e.Error);
}
else
{
logWriter.WriteToLog(this.jobSite + " - " + token + " (Email sent)");
try
{
int updated = UpdateMailQueue(token, now);
if (updated > 0)
{
// Update your log
}
}
catch (SqlException sqlEx)
{
LogError(sqlEx);
}
}
}
catch (ArgumentNullException argument)
{
LogError(argument);
}
finally
{
client.SendCompleted -= client_SendCompleted;
client.Dispose();
mail.Dispose();
// Delete the attachment if any, attached to this email
DeleteZipFile(token);
counter--;
}
};
client.SendAsync(mail, userState);
counter++;
}
catch (ArgumentOutOfRangeException argOutOfRange)
{
LogError(argOutOfRange);
}
catch (ConfigurationErrorsException configErrors)
{
LogError(configErrors);
}
catch (ArgumentNullException argNull)
{
LogError(argNull);
}
catch (ObjectDisposedException objDisposed)
{
LogError(objDisposed);
}
catch (InvalidOperationException invalidOperation)
{
LogError(invalidOperation);
}
catch (SmtpFailedRecipientsException failedRecipients)
{
LogError(failedRecipients);
}
catch (SmtpFailedRecipientException failedRecipient)
{
LogError(failedRecipient);
}
catch (SmtpException smtp)
{
LogError(smtp);
}
}
SendCompletedEvent 处理程序中捕获了错误。
当然,该错误仅出现在一封电子邮件中,而其他 7 封邮件在同一运行之前和之后都通过了不同的邮箱。是什么导致了错误,我仍然不知道。
当我再次运行我的程序时,它拿起了未发送的邮件并成功发送。
希望这可以帮助其他人,因为我意识到这个问题是在 15 个多月前发布的。