.Net, Programming

Send Email Asynchronously in .Net

If you use synchronous mode to send an email then the process for to sending email start by calling a method, then the application has to wait to complete and that time application is blocked or halted. In contrast, asynchronous mode to call the method that you define as background and that method, return to an application immediately no matter the running method is complete or not. That method has been run as background thread and completed automatically without disturbing current application UI.

Here you can find to send email asynchronously in .net using C# and VB.Net.

C#


using System;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading;
using System.ComponentModel;
namespace Examples.SmptExamples.Async
{
    public class AsyncEmail
    {
        static bool mailSent = false;
        private static void CompleteCallback(object sender, AsyncCompletedEventArgs e)
        {
            // Get the unique identifier for this asynchronous operation.
            String token = (string)e.UserState;

            if (e.Cancelled)
            {
                Console.WriteLine("[{0}] Send canceled.", token);
            }
            if (e.Error != null)
            {
                Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
            }
            else
            {
                Console.WriteLine("Message sent.");
            }
            mailSent = true;
        }

        public static void Main(string[] args)
        {
            SmtpClient Mailclient = new SmtpClient(args[0]);
            // the sender.
            MailAddress from = new MailAddress("support@techzigg.com", "Admin");
            // destinations
            MailAddress to = new MailAddress("test@techzigg.com");
            // the message text
            MailMessage message = new MailMessage(from, to);
            message.Body = "This is a test e-mail.";

            message.Subject = "Async Email Test";
            // Set the method that is called back when email sent.
            Mailclient.mailCompleted += new mailCompletedEventHandler(CompleteCallback);
            // userState can be any object that allows your callback
            // method to identify this send operation.
            string userState = "test Async";
            // To send async mail
            Mailclient.SendAsync(message, userState);
            Console.WriteLine("Sending message... press c to cancel mail.");
            string input = Console.ReadLine();
            // If the user canceled the send, and mail hasn't been sent yet,
            if (input.StartsWith("c") && mailSent == false)
            {
                Mailclient.SendAsyncCancel();
            }
            // Clean up.
            message.Dispose();
            Console.WriteLine("Thanks.");
        }
    }
}

VB.Net


Imports System.Net
Imports System.Net.Mail
Imports System.Net.Mime
Imports System.Threading
Imports System.ComponentModel

Namespace Examples.SmptExamples.Async
Public Class AsyncEmail

Shared mailSent As Boolean = False
Private Shared Sub CompleteCallback(sender As Object, e As AsyncCompletedEventArgs)
' Get the unique identifier for this asynchronous operation.
Dim token As [String] = DirectCast(e.UserState, String)
If e.Cancelled Then
Console.WriteLine("[{0}] Send canceled.", token)
End If
If e.Error IsNot Nothing Then
Console.WriteLine("[{0}] {1}", token, e.Error.ToString())
Else
Console.WriteLine("Message sent.")
End If
mailSent = True
End Sub

Public Shared Sub Main(args As String())
Dim Mailclient As New SmtpClient(args(0))
'the sender.
Dim from As New MailAddress("support@techzigg.com", "Admin")
'destinations
Dim to As New MailAddress("test@techzigg.com")
'the message text
Dim message As New MailMessage(from, to)
message.Body = "This is a test e-mail."

message.Subject = "Async Email Test"
' Set the method that is called back when email sent.
Mailclient.mailCompleted += New mailCompletedEventHandler(AddressOf CompleteCallback)
' userState can be any object that allows your callback
' method to identify this send operation.
Dim userState As String = "test Async"
' To send async mail
Mailclient.SendAsync(message, userState)
Console.WriteLine("Sending message... press c to cancel mail.")
Dim input As String = Console.ReadLine()
' If the user canceled the send, and mail hasn't been sent yet,
If input.StartsWith("c") AndAlso mailSent = False Then
Mailclient.SendAsyncCancel()
End If
' Clean up.
message.Dispose()
Console.WriteLine("Thanks.")
End Sub
End Class
End Namespace

Using SendAsync method you can send email asynchronously and in above code, there is error handling while sending a mail so you can get an error with a status code in a CompleteCallback method and even you can set multiple senders in this code.

2 thoughts on “Send Email Asynchronously in .Net

  1. Fantastic goods from you, man. I’ve understand your stuff
    prior to and you are just too wonderful. I actually like what you have received
    here, really like what you’re stating and the way wherein you assert it.
    You are making it entertaining and you continue to care for to
    stay it smart. I can’t wait to read much more from you.
    That is actually a terrific site.

Leave a Reply

Your email address will not be published. Required fields are marked *