我正在尝试使用SmtpClient.SendMailAsync方法发送大量电子邮件.
这是我从简单的控制台应用程序调用的测试方法.
static void Main(string[] args)
{
SendMailsOnebyOneAsync().GetAwaiter().GetResult();
}
public static async Task SendMailsOnebyOneAsync()
{
for (int i = 0; i < 1000; i++)
{
try
{
using (SmtpClient sMail = new SmtpClient("XXX"))
{
sMail.DeliveryMethod = SmtpDeliveryMethod.Network;
sMail.UseDefaultCredentials = false;
sMail.Credentials = null;
var fromMailAddress = new MailAddress("XXX");
var toMailAddress = new MailAddress("XXX");
MailMessage message = new MailMessage(fromMailAddress, toMailAddress)
{
Subject = "test"
};
await sMail.SendMailAsync(message);
Console.WriteLine("Sent {0}", i);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
有时这个方法是悬挂的 – 它等待SendMailAsync,它似乎卡住而且不会返回.
我看到一个相关的问题
SmtpClient SendMailAsync sometimes never returns
但没有任何修复建议对我有用.
当我尝试使用同步方法SmtpClient.Send时一切正常,应用程序永远不会挂起.
有谁知道出了什么问题?
解决方法:
使用一个客户端发送重复的邮件.不断创建和处置许多客户端可能会出现端口问题.
public static async Task SendMailsOnebyOneAsync() {
using (var sMail = new SmtpClient("XXX")) {
sMail.DeliveryMethod = SmtpDeliveryMethod.Network;
sMail.UseDefaultCredentials = false;
sMail.Credentials = null;
for (int i = 0; i < 1000; i++) {
try {
var fromMailAddress = new MailAddress("XXX");
var toMailAddress = new MailAddress("XXX");
var message = new MailMessage(fromMailAddress, toMailAddress) {
Subject = "test"
};
await sMail.SendMailAsync(message);
Console.WriteLine("Sent {0}", i);
} catch (Exception e) {
Console.WriteLine(e.Message);
}
}
}
}
其次,虽然可能就像这是一个例子,尝试一次发送许多电子邮件是不合理的.