Follow by Email

Friday, 18 January 2013

How to send automatic emails Or how to generate events automatically in particular time interval

Add new Global.asax file:

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

<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        // Code that runs on application startup
        System.Timers.Timer myTimer = new System.Timers.Timer();
        // Set the Interval to 5 seconds (5000 milliseconds).
        myTimer.Interval =
10000 ;
        //myTimer.Interval = 25000;
        myTimer.AutoReset = true;
        myTimer.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed);
        myTimer.Enabled = true;

    }


    public void myTimer_Elapsed(object source, System.Timers.ElapsedEventArgs e)
    {
        // use your mailer code
        MailTo objScheduleMail = new MailTo();
        objScheduleMail.SendScheduleMail();
    }

   
    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

    }

    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>

Now Add a new Class file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;

/// <summary>
/// Summary description for MailTo
/// </summary>
public class MailTo
{
    public MailTo()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public void SendScheduleMail()
    {
        // Write your send mail code here.
        MailMessage mail = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

        mail.From = new MailAddress("xyz@gmail.com");
        mail.To.Add("xyz@gmail.com");
        mail.Subject = "Test Mail";
        mail.Body = "This is for testing SMTP mail from GMAIL";

        SmtpServer.Port = 587;
        SmtpServer.Credentials = new System.Net.NetworkCredential("xyz@gmail.com","xyz123");
        SmtpServer.EnableSsl = true;

        SmtpServer.Send(mail);
       // MessageBox.Show("mail Send");
    }
}


0 comments:

Post a Comment


                                                            

 
Design by Abhinav Ranjan Sinha