Sending Automatic Mails in ASP.NET

The part of automatic sending mail can be done using a timer control from the ajax toolkit also but the main drawback is that you always have to check whether the system time is equal to 3'o clock or not so it unnecessarily waste the system's resources if we directly write the code in our aspx.cs file. So in order to increase the performance I've used BackgroundWorker class of System.ComponentModel.Component namespace.

The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.

To execute a time-consuming operation in the background, create a BackgroundWorker and listen for events that report the progress of your operation and signal when your operation is finished. You can create the BackgroundWorker programmatically or you can drag it onto your form from the Components tab of the Toolbox. If you create the BackgroundWorker in the Windows Forms Designer, it will appear in the Component Tray, and its properties will be displayed in the Properties window.

To set up a background operation, add an event handler for the DoWork event. Call your time-consuming operation in this event handler. To start the operation, call RunWorkerAsync. To receive notifications of progress updates, handle the ProgressChanged event. To receive a notification when the operation is completed, handle the RunWorkerCompleted event.

Enough of this theory, we'll go into the example just for testing purpose I've created a small but effective example. Following is the design code for the same.

Since background worker will create a different thread for executing the code of ours ie we can say that the code will be executed in an asynchronous manner, so we need to define the Async property of our page to true.

  1. <%@ Page Language="C#" AutoEventWireup="true" Async="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml" >  
  5. <head runat="server">  
  6.     <title>Untitled Page</title>  
  7. </head>  
  8. <body>  
  9.     <form id="form1" runat="server">  
  10.     <div>  
  11.         <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Send Mail" /></div>  
  12.     </form>  
  13. </body>  
  14. </html>  

Following is the source code for the same.

  1. using System;  
  2. using System.Data;  
  3. using System.Configuration;  
  4. using System.Web;  
  5. using System.Web.Security;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8. using System.Web.UI.WebControls.WebParts;  
  9. using System.Web.UI.HtmlControls;  
  10. using System.ComponentModel;// for backgroundworker class  
  11. using System.Net;  
  12. using System.Net.Mail;  
  13. using System.Threading;  
  14. public partial class _Default : System.Web.UI.Page   
  15. {  
  16.     BackgroundWorker bw;  
  17.     protected void Page_Load(object sender, EventArgs e)  
  18.     {  
  19.         bw = new BackgroundWorker();  
  20.         bw.DoWork+=new DoWorkEventHandler(bw_DoWork);  
  21.         bw.WorkerSupportsCancellation = true;  
  22.         bw.WorkerReportsProgress = false;  
  23.     }  
  24.     public void SendMail()  
  25.     {  
  26.         MailMessage msg = new MailMessage();  
  27.         msg.From = new MailAddress("[email protected]");  
  28.         msg.To.Add("[email protected]");  
  29.         msg.Body = "Testing the automatic mail";  
  30.         msg.IsBodyHtml = true;  
  31.         msg.Subject = "Movie Data";  
  32.         SmtpClient smt = new SmtpClient("smtp.gmail.com");  
  33.         smt.Port = 587;  
  34.         smt.Credentials = new NetworkCredential("Your Gmail Id""Your Password");  
  35.         smt.EnableSsl = true;  
  36.         smt.Send(msg);  
  37.         string script = "<script>alert('Mail Sent Successfully');self.close();</script>";  
  38.         this.ClientScript.RegisterClientScriptBlock(this.GetType(), "sendMail", script);  
  39.     }  
  40.     public void bw_DoWork(object sender, DoWorkEventArgs e)  
  41.     {  
  42.         SendMail();  
  43.     }  
  44.     protected void Button1_Click(object sender, EventArgs e)  
  45.     {  
  46.         DateTime current_time = DateTime.Now;  
  47.         current_time = current_time.AddSeconds(10);  
  48.         Thread.Sleep(10000);  
  49.         if (current_time == DateTime.Now)  
  50.         {  
  51.             bw.RunWorkerAsync();  
  52.         }  
  53.     }  
  54. }  

In this code after the user clicks the button the mail will be send automatically after 10 seconds to the specified email id.

Following is the output for the same.

MailASP1.gif

MailASP2.gif


Similar Articles