我正在开发一个ASP.NET MVC项目,管理员应该能够一次性向用户发送大约200封邮件(不,这不是垃圾邮件 - 这是一项服务,我保证!; - ))
我一直在寻找解决方案,因为我不想在for循环中使用client.Send();
,因为这可能会导致邮件无法发送。我读过的答案表明我们应该使用新线程发送邮件,并且我已经提出了以下帮助方法来发送邮件:
public static void SendEmails(string fromEmail, string subject, string bodyText, List<Customer> recepients)
{
try
{
// Loop through recepients and create a new mail message
foreach (var recepient in recepients)
{
var message = new MailMessage();
message.From = new MailAddress(fromEmail);
message.To.Add(recepient.Email);
message.Subject = subject;
message.Body = bodyText;
// Send the email async to avoid blocking the main thread
var client = new SmtpClient();
client.SendCompleted += (se, ea) =>
{
client.Dispose();
message.Dispose();
};
client.SendAsync(message, null);
}
}
catch
{
}
}
我的REST API控制器如下所示:
public bool SendMail(EmailRequest request)
{
bool result = false;
if (MemberHelper.IsLoggedIn() && MemberHelper.IsAdmin())
{
// Send emails
if (request.Customers != null)
{
MailHelper.SendEmails("my@email.com", request.EmailSubject, request.EmailBodyText, request.Customers);
}
}
return result;
}
当我调用SenMail rest方法时,我得到了这个例外:
An asynchronous module or handler completed while an asynchronous operation was still pending.
谁能告诉我这里做错了什么? : - )
提前致谢!