.Net, Programming

Send Bulk Emails Using Multi-Threading in .Net

If you use simple method call in for each loop to send bulk emails, for example, 1000 emails then you have been stuck in your application because of a single thread operated to send emails which are currently using the resources and thread of the application so to get the benefit of multi-threading is possible in .Net.
To use multi-threading in .Net you can use parallel for each to do initialize threads automatically in the scope of each loop.

First, you have to create, SendEmail method to send every method with some parameters like To, Subject and Message body.


private bool SendEmail(string To, string subject, string body)
 MailMessage msg = new MailMessage("sender@gmail.com", To);
 msg.Subject = subject;
 msg.Body = body;
 msg.IsBodyHtml = true;
 SmtpClient smtp = new SmtpClient();
 smtp.Host = "smtp.gmail.com";
 smtp.EnableSsl = true;
 NetworkCredential NetworkCred = new NetworkCredential();
 NetworkCred.UserName = "sender@gmail.com";
 NetworkCred.Password = "*password*";
 smtp.UseDefaultCredentials = true;
 smtp.Credentials = NetworkCred;
 smtp.Port = 587;
 return true;
{return false;}



Private Function SendEmail([To] As String, subject As String, body As String) As Boolean
Dim msg As New MailMessage("sender@gmail.com", [To])
msg.Subject = subject
msg.Body = body
msg.IsBodyHtml = True
Dim smtp As New SmtpClient()
smtp.Host = "smtp.gmail.com"
smtp.EnableSsl = True
Dim NetworkCred As New NetworkCredential()
NetworkCred.UserName = "sender@gmail.com"
NetworkCred.Password = "*password*"
smtp.UseDefaultCredentials = True
smtp.Credentials = NetworkCred
smtp.Port = 587
Return True
Catch generatedExceptionName As ex
Return False
End Try
End Function

Now implement multi-threading to send email using Parallel.ForEach as below:

// Parallel Multi-Threading send multiple bulk email.
Parallel.ForEach(Email Obj in List)
if (!(SendEmail(Obj.Email, "test email", Obj.Name)))


' Parallel Multi-Threading send multiple bulk email.
Parallel.ForEach(Obj as Email in List)
IF (Not(SendEmail(Obj.Email, "test email", Obj.Name)))
Exit For

So SendEmail method called multiple times as parallel way and automatically use multi thread to do your email sending process faster so you can easily send bulk emails using .Net even thousand emails.

Leave a Reply

Your email address will not be published. Required fields are marked *