BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Network and Internet
.NET 2.0+

Sending SMTP Email Asynchronously

Sending email using the Simple Mail Transport Protocol (SMTP) can be a slow process, particularly when sending large numbers of messages using, for example, a bulk email tool. This process can be accelerated with considered use of asynchronous sending.

Cancelling an Email

As mentioned previously, the asynchronous delivery of an email can be cancelled if the message has not yet been sent to an SMTP server. To cancel such a message, the SendAsyncCancel method of the SmtpClient object is called. The sending operation still causes the SendCompleted event to be raised. However, the event arguments passed indicate that the operation was cancelled.

To demonstrate the cancellation of an email, modify the Main method of the program as follows, then execute it.

private static void CancelAynchronousEmail(SmtpClient client)
{
    MailMessage message = new MailMessage();
    message.To.Add(RecipientEmail);
    message.From = new MailAddress(SenderEmail);
    message.Subject = "Asynchronous Email Test";
    message.Body = "This is a test email, sent asynchronously.";
    client.SendCompleted += new SendCompletedEventHandler(MailDeliveryComplete);
    client.SendAsync(message, "Test");
    client.SendAsyncCancel();

    Console.WriteLine("Main program finished.");
    Console.ReadLine();
}

/* OUTPUT

Main program finished.
Message "Test".
Sending of email cancelled.

*/
15 June 2008