Here is the set-up:
- I have a Notifications controller that is called from task scheduler 1x/day
- The action method pulls upwards of 300 addresses, loops thru them and uses the SmtpClient class to send an individual e-mail to each recepient.
From what I can tell the process runs fine with no exceptions ... except that not all e-mails are being delivered. Anyone have any ideas on what is going on and how to resolve?
Here is the code:
foreach (var emp in division.Users)
{
var fromAddress = "myfromaddress";
var mailServer = "mymailserver";
var toEmail = emp.EmailAddress;
var message = new MailMessage(fromAddress, toEmail)
{
Subject = subject,
Body = "<body style='font:normal 13px tahoma,arial,helvetica;'>" + body + "</body>",
IsBodyHtml = true
};
var client = new SmtpClient(mailServer);
client.Send(message);
}
UPDATE:
Adding a pause in between sending e-mails resolves the problem. But why does this work? And is there a better way (e.g. using Async()) that would equally resolve the issue in a better way???
Updated code ...
foreach (var emp in division.Users)
{
var fromAddress = "myfromaddress";
var mailServer = "mymailserver";
var toEmail = emp.EmailAddress;
var message = new MailMessage(fromAddress, toEmail)
{
Subject = subject,
Body = "<body style='font:normal 13px tahoma,arial,helvetica;'>" + body + "</body>",
IsBodyHtml = true
};
var client = new SmtpClient(mailServer);
client.Send(message);
Thread.Sleep(3000); // Wait 3s until sending next message
}