I've a problem with sending a newsletter (to about 5000 people) in my mvc-helper class.
public static void SendNewsletter(string fromAccount, string subject, string eMailText)
{
var userEMailAddresses = new List<string>();
using (var dbContext = new dbEntities())
{
userEMailAddresses =
dbContext
.User
.Where(w =>
!w.IsDeactivated &&
!w.IsBlacklisted)
.Select(s =>
s.UserName)
.ToList();
}
new Thread(() =>
{
for (int i = 0; i < userEMailAddresses.Count; i++)
{
SendMail(fromAccount, userEMailAddresses[i], subject, eMailText);
}
}).Start();
}
This is my function which will be called in a controller. The next Code-Block is the sending function.
public static void SendMail(string fromAccount, string toAccount, string subject, string eMailText)
{
var fromEmailAddress = new EMailModel(fromAccount);
var body = string.Empty;
using (var sr = new StreamReader(HostingEnvironment.MapPath("\\App_Data\\Templates\\") + "EMailTemplate.txt"))
{
body = sr.ReadToEnd();
}
body = body.Replace("%%Subject%%", subject);
body = body.Replace("%%Body%%", eMailText);
body = body.Replace("%%Year%%", DateTime.Now.Year.ToString());
using (MailMessage mail = new MailMessage(fromEmailAddress.EMailAddress, toAccount))
{
mail.Subject = subject;
mail.Body = WebUtility.HtmlDecode(body);
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(Statics.SmtpClient, Statics.SmtpPort))
{
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(fromEmailAddress.EMailAddress, fromEmailAddress.Password);
smtp.EnableSsl = Statics.SslEnabled;
try
{
smtp.Send(mail);
Thread.CurrentThread.Join(1000);
}
catch (Exception ex) {
throw ex;
}
}
}
}
After approx 1300 emails, my IIS get the following error:
How can I solve this problem? I need the newsletter system...