Sending Email with the Simple Mail Transport Protocol (SMTP) may be a pretty slow process, particulary if you send a lot of mail message at the same time and so can be slow your application process.
Deliver Mail Message with .NET is possible with the SmtpClient class of System.Net.Mail namespace.
In this article you will learn howto send smtp email asynchronously.
Here is a short sample for sending smtp mail asynchronously.
static void Main(string[] args)
{
MailMessage message = new MailMessage();
message.To.Add(MailAddress);
message.From = new MailAddress(MailFrom);
message.Subject = "Asynchronous Email Test";
message.Body = "This is a async test email.";
SendEmail(message);
SendEmailWithCancel(message);
Console.WriteLine("Main program finished.");
Console.ReadLine();
}
SmtpClient.SendAsync Method
/// <summary>
/// Sends the email.
/// </summary>
/// <param name="message">The message.</param>
private static void SendEmail(MailMessage message)
{
SmtpClient smtp = new SmtpClient(MailServer);
smtp.SendCompleted += new SendCompletedEventHandler(SendCompleted);
smtp.SendAsync(message, "Test");
}
SmtpClient.SendCompleted Event
The SendCompleted Event provides 3 argument to control mail processing
- Error (Boolean) : if an error occurs this argument equals "True"
- Cancelled (Boolean) : if the process is cancelled, this argument equals "True"
- UserState (Object) : Represents a UserToken passed to the SendAsync Method
In order to capture this event we need to add it to the SmtpClient.SendCompleted event collection.
smtp.SendCompleted += new SendCompletedEventHandler(SendCompleted);
And here is the Implementation of the SendCompleted Event Method.
/// <summary>
/// Sends the completed.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The <see cref="System.ComponentModel.AsyncCompletedEventArgs"/>
/// instance containing the event data.</param>
static void SendCompleted(object sender, AsyncCompletedEventArgs e)
{
Console.WriteLine("Message {0}", e.UserState);
if (e.Error != null)
Console.WriteLine("Error sending email");
else if (e.Cancelled)
Console.WriteLine("Sending of email cancelled");
else
Console.WriteLine("Message sent");
}
SmtpClient.SendAsyncCancel Method
/// <summary>
/// Sends the email with cancel.
/// </summary>
/// <param name="message">The message.</param>
private static void SendEmailWithCancel(MailMessage message)
{
SmtpClient smtp = new SmtpClient(MailServer);
smtp.SendCompleted += new SendCompletedEventHandler(SendCompleted);
smtp.SendAsync(message, "Test");
smtp.SendAsyncCancel();
}
Hope this Help's
Views(2667)

