I have an MVC3 web application and i am using MvcMailer to send out email (potentially thousands at once). This is working fine if i just BCC each recipient into the same email, but if i try to loop through them sending them individual emails it is incredibly slow, which i guess is because it is connecting to the smtp server again each time?
We have our own smtp server which it is connecting to, and i am currently attempting to send the emails like this:
foreach(Person x in names)
{
var mail = Mailer.Example_Mail()
mail.To.Add(x.Email_Address);
mail.Send();
}
I know from the tutorial that you can save the emails to a file instead of connecting to the smtp server and sending them immediately, and i also know from the accepted answer on this post that you can have IIS pick them up and send them, but unfortunately i have no idea how.
If some one could let me know what the best way of doing this is that would be awesome! thank you all in advance!
UPDATE
I have tried using the SendAsync()
method as suggested by @Mike, which does indeed speed things up considerably, but its now losing ~40% of the emails. With no errors being thrown only about 65 of every 100 emails gets through. I tried to catch any errors as suggested here in the "Handle Events for Asynchronous Email" section, but none seem to be thrown at all. Code below:
List<object> errors = new List<object>();
var mail = Mailer.Example_Mail();
mail.To.Add("some@address.com");
for (int i = 0; i < 100; i++)
{
var client = new SmtpClientWrapper();
client.SendCompleted += (sender, e) =>
{
if (e.Error != null || e.Cancelled)
{
errors.Add(e);
}
};
mail.SendAsync("user state object", client);
}