We have a website and we just ran into a problem when trying to send 700 emails in one bulk. I'm thinking it's better to send 100 emails 7 times but which approach should I take?
Here's my code:
protected void btnClick_Send(object sender, EventArgs e)
{
MailMessage mailObj = new MailMessage();
mailObj.Bcc.Add(txtReciever.Text.Trim());
mailObj.ReplyToList.Add("our-reply-email@oursite.com");
mailObj.SubjectEncoding = System.Text.Encoding.UTF8;
mailObj.BodyEncoding = System.Text.Encoding.UTF8;
mailObj.Subject = txtSubject.Text;
mailObj.Body += Environment.NewLine;
mailObj.Body = txtContent.Text;
mailObj.Body += Environment.NewLine;
SmtpClient SMTPServer = new SmtpClient();
SMTPServer.Send(mailObj);
}
Any other ideas?
This is definitely one of those embarrassingly parallel problems, which would gain great benefit from parallelism.
In .NET 4.0 you can have that code run in parallel by simply using the Parallel.ForEach method.
Assuming that messages
is a sequence of objects containing the Receiver
, Subject
and Body
of the e-mails to send, this example uses the Task Parallel Library to automatically send as many of them as possible out in parallel given the resources available on the machine:
Parallel.ForEach(messages, message =>
{
MailMessage mailObj = new MailMessage();
mailObj.Bcc.Add(message.Receiver);
mailObj.ReplyToList.Add("our-reply-email@oursite.com");
mailObj.SubjectEncoding = System.Text.Encoding.UTF8;
mailObj.BodyEncoding = System.Text.Encoding.UTF8;
mailObj.Subject = message.Subject;
mailObj.Body += Environment.NewLine;
mailObj.Body = message.Body;
mailObj.Body += Environment.NewLine;
SmtpClient SMTPServer = new SmtpClient();
SMTPServer.Send(mailObj);
}
Of course, you can implement the same solution in .NET 2.0 as well, for example using the ThreadPool.QueueUserWorkItem method to manually schedule the e-mails to be sent out on different threads, but it would definitely require more effort.