When we need to send bunch of emails, sending them synchronously will take much time. So one way to solve this problem is to send emails asynchronously. Sending emails asynchronously is very simple. And to handle call backs we need to associate one method to SendCompletedEventHandler. It will be called once the email has been sent. We need one smtp network host provider which will be configured in Smtp.config or Web.config. The sample code looks as below.
- public void SendEmailsAsync()
- {
- var smtpSection = (SmtpSection) ConfigurationManager.GetSection("system.net/mailSettings/smtp");
- var mailClient = new SmtpClient(smtpSection.Network.Host);
- mailClient.SendCompleted += new SendCompletedEventHandler(SendCompleted);
- mailClient.EnableSsl = false;
- var mailMessage = new MailMessage("sender email", "to address")
- {
- IsBodyHtml = true,
- Subject = "subject",
- Body = "body"
- };
- Object obj = meilMessage;
- mailClient.SendAsync(mailMessage, obj);
- }
-
- public void SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e) {
-
- if (!e.Cancelled && e.Error != null)
- {
-
- }
- }
In the above example we are reading smpt configurations from smtp.config. You need to define network host which will take care of sending emails. The configuration looks as below.
- <?xml version="1.0"?>
- <smtp from="sender email id">
- <network host="Your smtp host name" />
- </smtp>
If you are calling
SendEmailsAsync() in a for loop then the main thread will not wait until all call back completed. It will exit immediately. So here we need to handle wait mechanism. The final code to handle this will be as below. - public void SendEmailsAsync()
- {
- int remainingCalls = 0;
- public object RemainingCallLock = new object();
- for (int i = 0; i < noOfEmails; i++)
- {
-
- var smtpSection = (SmtpSection) ConfigurationManager.GetSection("system.net/mailSettings/smtp");
- var mailClient = new SmtpClient(smtpSection.Network.Host);
- mailClient.SendCompleted += new SendCompletedEventHandler(SendCompleted);
- mailClient.EnableSsl = false;
- var mailMessage = new MailMessage("sender email", "to address")
- {
- IsBodyHtml = true,
- Subject = "subject",
- Body = "body"
- };
- Object obj = meilMessage;
- mailClient.SendAsync(mailMessage, obj);
- RemaingingCalls++;
- }
- if (RemaingingCalls > 0) WaitHandle.WaitOne();
-
- }
-
- public void SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
- {
-
- if (!e.Cancelled && e.Error != null)
- {
-
- lock(RemainingCallLock) {
- if (--RemaingingCalls == 0)
- {
- WaitHandle.Set();
- }
- }
- }
- }
In the above example WaitHandle.WaitOne() will pause the current thread until all requested are handled. Once all requests are handled we are releasing the lock by calling WaitHandle.Set().