SIGN UP MEMBER LOGIN:    
ARTICLE

Sending Automatic Mails in ASP.NET

Posted by Vishal Gilbile Articles | ASP.NET Programming September 19, 2011
In this project I was asked to send an automatic mail to the person in charge after the movies 1 hour ie if the show time is 2’o clock then the automatic mail should be sent at 3’o clock and finally it should logout of the application.
Reader Level:
Download Files:
 

At a times there becomes a requirement to send automatic mail to a particular no of clients in our web projects. Recently working on a web project which basically deals with Ticket issue of movies. In this project I was asked to send an automatic mail to the person in charge after the movies 1 hour ie if the show time is 2'o clock then the automatic mail should be sent at 3'o clock and finally it should logout of the application.

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.

<%@ Page Language="C#" AutoEventWireup="true" Async="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title
>
</head>
<
body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Send Mail" /></div>
    </form
>
</body>
</
html>

Following is the source code for the same.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.ComponentModel;// for backgroundworker class
using System.Net;
using System.Net.Mail;
using System.Threading;
public partial class _Default : System.Web.UI.Page
{
    BackgroundWorker bw;
    protected void Page_Load(object sender, EventArgs e)
    {
        bw = new BackgroundWorker();
        bw.DoWork+=new DoWorkEventHandler(bw_DoWork);
        bw.WorkerSupportsCancellation = true;
        bw.WorkerReportsProgress = false;
    }

    public void SendMail()
    {
        MailMessage msg = new MailMessage();
        msg.From = new MailAddress("cinema.nandi@gmail.com");
        msg.To.Add("vishalgilbile@rediffmail.com");
        msg.Body = "Testing the automatic mail";
        msg.IsBodyHtml = true;
        msg.Subject = "Movie Data";
        SmtpClient smt = new SmtpClient("smtp.gmail.com");
        smt.Port = 587;
        smt.Credentials = new NetworkCredential("cinema.nandi@gmail.com", "nandi@123");
        smt.EnableSsl = true;
        smt.Send(msg);
        string script = "<script>alert('Mail Sent Successfully');self.close();</script>";
        this.ClientScript.RegisterClientScriptBlock(this.GetType(), "sendMail", script);
    }
    public void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        SendMail();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {

        DateTime current_time = DateTime.Now;
        current_time = current_time.AddSeconds(10);
        Thread.Sleep(10000);
        if (current_time == DateTime.Now)
        {
            bw.RunWorkerAsync();
        }
    }
}


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

Login to add your contents and source code to this article
share this article :
post comment
 

Thread is a small piece of work or unit of work within a process. Generally a process consists of number of thread. Take a simple example when we play videogame our screen background changes simultaneously our speed counter changes and at the same time sound effects also changes and many other things are done at same time. so generally we can say that these activities are nothing but thread's. There are two types of thread 1. Single thread Application 2. Multi Thread application The game scenario depicts multi thread application coz multiple threads are running at the same point of time. In this article I've used threading coz I want once the button is clicked after 10 seconds of that the mail has to be sent so inorder to block the activity for 10 sec I've used threading concept. But if with advance technology like asp.net 3.5 or asp.net 4.0 we can make use of timer control to send the email after a specific period of time.

Posted by Vishal Gilbile Sep 22, 2011

Hi What is Thread in ASP.NET.

Posted by Rajesh Kumar Sep 22, 2011
Nevron Gauge for SharePoint
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor