Send asynchronous e-mail in C#

When developing an application, we generally use an auto e-mail functions to send notification, information, etc. to user. When sending an e-mail in C# we use System.Net.Mail Namespace and SmtpClient Class to send the specified message to a SMTP server for delivery. But, Send method is a synchronous method. It means, send method blocks while the e-mail is transmitted and user waits for the response and also ui is blocked.

What about if we want to send an e-mail asynchronously? User clicks send e-mail button or starts any action on the ui and e-mail is sending asynchronously. It means, user can continue work on the ui and shows an information to user on the ui when message is transmitted. It sounds good.

I have created an e-mail functionality class to send e-mail in C#. And it has send asynchronously capability. I hope it will be useful for you.

Properties of e-mail class :
object Token : A user-defined object that is passed to the method invoked when the asynchronous operation completes.(use when IsAsync = true)

EmailSettings.NetworkSettings NetworkSettings : Network settings of SMTP

string From : From address for e-mail message

string[] To : Recipient(s) of e-mail message

string[] CC : CC recipient(s) of e-mail message

string[] Bcc : Bcc recipient(s) of e-mail message
  
string Subject : Subject of e-mail message

string Body : E-mail message body

bool IsBodyHtml : Set true if body of e-mail message is in Html.

bool IsAsync : Set true to send e-mail asynchronously.

When you want to send e-mail:
// set network settings of SMTP server
EmailSettings.NetworkSettings networkSettings = 
    new EmailSettings.NetworkSettings(host, port, userName, password, enableSsl);

// create and e-mail
Email email = new Email();
// set properties
email.NetworkSettings = networkSettings;
email.From = ...
email.To = ...
email.Subject = ...
email.Body = ...
// send e-mail
email.Send();

If you want to send e-mail asynchronously, just set asynchronous properties of email object.
// set async properties and events
email.IsAsync = true;
email.Token = _asyncToken;
email.SendCompleted += new Email.SendCompletedEventHandler(email_SendCompleted);

and create a SendCompleted event
void email_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
    if ((int)e.UserState == _asyncToken)
    { 
        // do something, for example show notification to user
    }
}

You can find source code and sample usage on

0 comments:

Post a Comment