Sending Automatic mail through ASP.NET


In my previous article of sending automatic mail through asp.net we saw about how to send a mail at a particular time after a particular thing has happened. If you have not come across the example kindly click on the below link.

http://www.c-sharpcorner.com/UploadFile/17e8f6/9324/

The part which I've explained there that same concept can only be done by using a  Background worker class of System.ComponentModel namespace. Over there we've used Thread class Sleep method to hold the sleep the currently running thread for a specific period of time.

In this article we'll try to make use a of Session and we'll store the value in the session and after a specific interval if the session value is equal to that of the current systems time value then we'll try to send the mail.

For doing this activity, we require some basic features of Ajax control such as script manager, Timer control and updatepanel.

The following is the design of our Webpage.

<%@ 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></title
>
</head>
<
body>
    <form id="form1" runat="server">
    <div
>

        <asp:ScriptManager ID="ScriptManager1" runat="server" AsyncPostBackTimeout="600">
        </asp:ScriptManager>
        <asp:Timer ID="Timer1" Interval="3000" OnTick="Timer1_Tick" Enabled="false" runat="server">
        </asp:Timer>
        <br />
        <asp:UpdatePanel ID="updPanel" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                     <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Auto Send Mail Test" />    
            </ContentTemplate>
            <Triggers>
                     <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
            </Triggers>
        </asp:UpdatePanel>
        <br
/>

    </div>
    </form
>
</body>
</
html>

Note:

  1. In the above file, we've set the Async property at the page level to true, this is because since we are trying to perform an asynchronous operation. So we need to set this property.

  2. By default we've disable the timer control by setting the Enabled property to false.

  3. We've set the Interval property of the Timer control to 3000 milli seconds i.e. the tick event of the timer control will be called after every 3 sec you can increase or decrease the time period as per your program's need.

I've added a special file named Global.asax to create a session object.

The following is the source code.

<%@ Application Language="C#" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {
      
// Code that runs on application startup

  }

       void Application_End(object sender, EventArgs e)
    {
        //  Code that runs on application shutdown
       
    }

    void Application_Error(object sender, EventArgs e)
    {
       
// Code that runs when an unhandled error occurs

    }

    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started
        Session["maxIssue"] = 0;
    }

    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends.
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer
       
// or SQLServer, the event is not raised.

    }

</script>

The following is the code file for the same

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;//for background worker class
using Microsoft.VisualBasic;//for interacation message box
using System.Net;
using System.Net.Mail;
public partial class _Default : System.Web.UI.Page
{
    DateTime hours;
    BackgroundWorker bw = new BackgroundWorker();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            hours = Convert.ToDateTime(DateTime.Now.TimeOfDay.ToString());
            hours = hours.AddMinutes(1);
            Session["maxIssue"] = hours;
            Interaction.MsgBox(Session["maxIssue"].ToString(), MsgBoxStyle.Information, "Sesssion Saved Time");
        }
    }
    protected void Timer1_Tick(object sender, EventArgs e)
    {
        bw.DoWork += new DoWorkEventHandler(bw_DoWork);
        bw.WorkerReportsProgress = false;
        bw.WorkerSupportsCancellation = true;
        bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
        bw.RunWorkerAsync();
    }
    public void bw_DoWork(object sender, DoWorkEventArgs e)
    {
        Session.Timeout = 20;
        DateTime d = Convert.ToDateTime(Session["maxIssue"].ToString());
        //Interaction.MsgBox("D value is :" + d, MsgBoxStyle.Information, "Date Value");
        if (d <= DateTime.Now)
        {
            Timer1.Enabled = false;//for stopping the timer once the mail is sent.
            Interaction.MsgBox("Mail Sent" + DateTime.Now.ToString(), MsgBoxStyle.Information, "Mail Sent");
            SendMail();
        }
    }
    public void SendMail()
    {
        MailMessage msg = new MailMessage();
        msg.From = new MailAddress("[email protected]");
        msg.To.Add("[email protected]");
        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("your login account", "your word");
        smt.EnableSsl = true;
        smt.Send(msg);
        string script = "<script>alert('Mail Sent Successfully');self.close();</script>";
        this.ClientScript.RegisterClientScriptBlock(this.GetType(), "sendMail", script);
    }
    public static void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
            Button1.Enabled = false;
            Timer1.Enabled = true;
    }
}


Now try running the example.  Once the page is displayed, click the button and after 1 minute the mail will be sent automatically by the background worker class. You can increase the time, since in this example, while storing the time in the session I've only increased the time duration by 1 minute you can increase it by 1 hour or as your program needs.

Hope you've liked the example and it may help you in your project.
 

Up Next
    Ebook Download
    View all
    Learn
    View all