BlackWaspTM
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.

Sending SMTP Email Synchronously

Electronic mail can be delivered from .NET applications using the Simple Mail Transport Protocol (SMTP). This is the standard for sending email via the Internet. To learn how to send email, refer to the article, "Sending SMTP Email", which uses synchronous methods to deliver the messages to an SMTP server.

The delivery method described in the above article is simple and provides acceptable performance for a small number of emails. However, as each request blocks the calling thread, the program can spend a significant proportion of its time waiting for the SMTP server to respond.

Sending SMTP Email Asynchronously

If performance in an application is important and the synchronous method of sending email is causing a bottleneck, email can be delivered to an SMTP server asynchronously. Using this approach, a mail message is sent to the SMTP server using a separate thread so that the current thread is not blocked whilst it awaits a response. Depending upon the application, this can give a real or perceived performance gain by allowing the program to complete other tasks in parallel to the email operation.

SmtpClient.SendAsync Method

SMTP email can be sent using the SendAsync method of the SmtpClient class. This method is syntactically similar to the standard Send method with the additional of one parameter. The parameter permits a user token to be specified. The user token is an object of any type, usually used to uniquely identify the email. In the following sample program, the user token is a string containing the word "Test".

NB: Executing this code requires constants to be configured in the manner described in the article "Sending SMTP Email". The ReadLine call waits for the user to press Enter, which also provides a little time to allow the message to be sent before the program is terminated. In your own real-world applications, you should use another method of ensuring that the message has been delivered before exiting.

static void Main(string[] args)
{
    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.SendAsync(message, "Test");

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