Skip to main content

How to send mail asynchronously in asp.net

With Microsoft.NET Framework 2.0 everything is asynchronous and we can send mail also asynchronously. This features is very useful when you send lots of bulk mails like news letter. You don’t have to wait for response from mail server and you can do other task .

Let's create a simple example to send mail. For sending mail asynchronously you need to create a event handler that will notify that mail successfully sent or some errors occurred during sending mail. Let’s create a mail object and then we will send it asynchronously. You will require System.Net.Mail space to import in your page to send mail.

//you require following name space
using System.Net.Mail;

//creating mail message object
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress("Put From mail address here");
mailMessage.To.Add(new MailAddress("Put To Email Address here"));
mailMessage.CC.Add(new MailAddress("Put CC Email Address here"));
mailMessage.Bcc.Add(new MailAddress("Put BCC Email Address here"));
mailMessage.Subject = "Put Email Subject here";
mailMessage.Body = "Put Email Body here ";
mailMessage.IsBodyHtml = true;//to send mail in html or not


SmtpClient smtpClient = new SmtpClient("Put smtp server host here", 25);//portno here
smtpClient.EnableSsl = false; //True or False depends on SSL Require or not
smtpClient.UseDefaultCredentials = true ; //true or false depends on you want to default credentials or not
Object mailState = mailMessage;

//this code adds event handler to notify that mail is sent or not
smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
try
{
smtpClient.SendAsync(mailMessage, mailState);
}
catch (Exception ex)
{
Response.Write(ex.Message);
Response.Write(ex.StackTrace);
}
Following is a code for event handler

void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
MailMessage mailMessage = e.UserState as MailMessage;
if (!e.Cancelled && e.Error != null)
{
Response.Write("Email sent successfully");
}
else
{
Response.Write(e.Error.Message);
Response.Write(e.Error.StackTrace);
}
}
So that’s it you can send mail asynchronously this 30-40 lines of code.

Technorati Tags: ,

Shout it

kick it on DotNetKicks.com

Comments

  1. if I want to send a thousand of email from web page then it takes so much time to postback the page, do you have any other solution for this?

    ReplyDelete
  2. Why just not use ThreadPool.QueueUserWorkItem() method?

    ReplyDelete
  3. hi

    i have tried your code it give this error

    any idea how to resolve this

    Failure sending mail. at System.Net.Mail.SmtpClient.SendAsync(MailMessage message, Object userToken)

    ReplyDelete
  4. Hi Can you send me your code please. Because its working fine. Did you configured your smtp settings properly?

    ReplyDelete
  5. yes , here its

    //creating mail message object
    MailMessage mailMessage = new MailMessage();
    mailMessage.From = new MailAddress("mymail@gmail.com");
    mailMessage.To.Add(new MailAddress("yyyyyy@gmail.com"));
    mailMessage.CC.Add(new MailAddress("xxxxxxxx@gmail.com"));
    mailMessage.Bcc.Add(new MailAddress("zzzzzzzz@gmail.com"));
    mailMessage.Subject = "Email Checking Asynchronously";
    mailMessage.Body = "Email test asynchronous";
    mailMessage.IsBodyHtml = true;//to send mail in html or not


    SmtpClient smtpClient = new SmtpClient();//portno here
    smtpClient.Host = "smtp.gmail.com";
    smtpClient.EnableSsl = true ; //True or False depends on SSL Require or not
    smtpClient.Credentials = new NetworkCredential("mymail@gmail.com", "mypassword");
    //smtpClient.UseDefaultCredentials = true; //true or false depends on you want to default credentials or not
    Object mailState = mailMessage;

    //this code adds event handler to notify that mail is sent or not
    smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
    try
    {
    smtpClient.SendAsync(mailMessage, mailState);
    }
    catch (Exception ex)
    {
    Response.Write(ex.Message);
    Response.Write(ex.StackTrace);
    }

    }

    void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
    {
    MailMessage mailMessage = e.UserState as MailMessage;
    if (!e.Cancelled && e.Error != null)
    {
    Response.Write("Email sent successfully");
    }
    else
    {
    Response.Write(e.Error.Message);
    Response.Write(e.Error.StackTrace);
    }
    }

    ReplyDelete
  6. Hi Vekant,

    When you write

    smtpClient.SendAsync(mailMessage, mailState);

    After this code will not wait because it async so whenever the operation is completed it will fire that event and you can continue work on other task after this line.

    ReplyDelete
  7. Also please tell me what is the error are you giving right credentials.

    ReplyDelete
  8. hi i got the answer ie: i posted the issue on forums i got it

    so you have to change the code

    on page_Directive Async="true"

    then change this code its working. so do the same on your post too.

    void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
    {
    MailMessage mailMessage = e.UserState as MailMessage;
    if (e.Cancelled || e.Error != null)
    {

    Response.Write(e.Error.Message);
    Response.Write(e.Error.StackTrace);
    }
    else
    {
    Response.Write("Email sent successfully");
    }
    }

    ReplyDelete
  9. any sample is I use it in asp.net web ?? How can I show message to user in page.aspx when it execute smtpClient_SendCompleted event ?? thanks.

    ReplyDelete

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Popular posts from this blog

How to create Rest API(Web API) with ASP.NET Core 1.0

Recently Microsoft has released ASP.NET Core 1.0 RC2, I am getting lots of request from readers that about creating Web API. So I thought it will be a good idea to write a blog post about how to create Rest API(Web API) with ASP.NET Core 1.0.

So let’s get started via creating an ASP.NET Core 1.0 Web Application like following.



Once you click on ASP.NET Web Application, It will ask whether you need to create Web Application or Web API application. We are going to Web API so I am going to select Web API Application like following. Please note that in ASP.NET Core 1.0 there is no separate libraries or DLLs required for creating web APIs. This is just a project template.



Now once you click on OK It will create a Web API application with default values controller and program.cs.  As you know Program.cs is now starting point for the ASP.NET Core 1.0 application so It contains all the required configuration and startup items. Following is a code for that.
using System.IO; using Microsoft.Asp…

How to use migration with Entity Framework Core

Entity framework core is  the lightweight, extensible and cross-platform version of Entity Framework. Before some time, Microsoft has Released a new version of Entity Framework RC2. I have written a couple of blog post about Entity framework code first migration earlier for Entity framework 6.0. So there was a couple of request coming for writing a blog post about Entity Framework Core RC2 migration. So I thought it will be a good idea to give an overview how database migration works in Entity Framework Core RC2. This post will cover a basic scenario where we are going to create the database with existing ASP.NET Identity migration and then we are going to create a new model and have that migration applied in the database.

How to use Entity Framework Migrations: Let’s get started, To demonstrate entity framework core migrations, I am going to create a sample asp.net core web application like following.



Once we select asp.net core application it will appear the following dialog.



Now w…

Creating PDF with ASP.Net MVC and RazorPDF

Update: I have written a new blog post about better approach to create a PDF with asp.net mvc- You can find that following location.- A Better Solution to create PDF with Rotativa and ASP.NET MVC
In this post we are going to learn how we can easily create PDF from ASP.Net application with the help of Razor PDF NuGet package.

About Razor PDF:
This NuGet package is created by Al Nyveldt It internally uses ITextSharp an open source PDF convertor library. RazorPDF uses Razor View engine to create iTextXML which is in tern used to produce PDF file. You can get more information about that at below link.

https://www.nuget.org/packages/RazorPDF

Example(Creating PDF with ASP.Net MVC):
So what we are we waiting for ? Let’s create a simple example. To create example first thing we need to a create and ASP.Net MVC application.