JRHeaven : Free Computer Books, IT Books, Project Guidelines, Novels and Many More...

Monday, June 22, 2015

Create Windows Service to send mail daily using ASP.Net and C#


This article explains, How to create Windows Service in ASP.Net with C# to send mail on daily basis. So, we explain this step by step as following :


STEP 1 : 

Create Windows Service Proejct in Microsoft Visual Studio 2012 and give project name as   "WindowsServiceProject1".

STEP 2 : 

Now update your App.Config file as follow :
<configuration>
  <appSettings>
    <add key="StartTime" value="03:50 PM "/>
    <add key="callDuration" value="2"/>
    <add key="CallType" value="1"/>
    <add key="FromMail" value="your_from_email_id@gmail.com"/>
    <add key="Password" value="your_email_id_password"/>
    <add key="Host" value="smtp.gmail.com"/>
  </appSettings>
  <system.net>
    <mailSettings>
      <smtp from="your_from_email_id@gmail.com">
        <network host="smtp.gmail.com" userName="your_from_email_id@gmail.com" password="your_email_id_password" enableSsl="true" port="587" />
      </smtp>
    </mailSettings>
  </system.net>
</configuration>
In this configuration settings, we use gmail email id to send mail, so for that we use smtp.gmail.com as host and Port number 587.



STEP 3 :

Now add one new class called "SendMailService.cs" in your project and add the following namespace and methods inside the class.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;

// This function write log to LogFile.text when some error occurs.  
 public static void WriteErrorLog(Exception ex)
 {
      StreamWriter sw = null;
      try
      {
                sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + \\LogFile.txt", true);
                sw.WriteLine(DateTime.Now.ToString() + ": " + ex.Source.ToString().Trim() + "; " + ex.Message.ToString().Trim());
                sw.Flush();
                sw.Close();
      }
      catch
      {
      }
}
// This function write Message to log file.
 public static void WriteErrorLog(string Message)
 {
      StreamWriter sw = null;
      try
      {
                sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + \\LogFile.txt", true);
                sw.WriteLine(DateTime.Now.ToString() + ": " + Message);
                sw.Flush();
                sw.Close();
      }
      catch
      {
      }
}
// This function contains the logic to send mail.
 public static void SendEmail(String ToEmail, String Subj, string Message)
 {
      try
      {
                System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
                smtpClient.EnableSsl = true;
                smtpClient.Timeout = 200000;
                MailMessage MailMsg = new MailMessage();
                System.Net.Mime.ContentType HTMLType = new System.Net.Mime.ContentType("text/html");

                string strBody = "This is a test mail.";
               
                MailMsg.BodyEncoding = System.Text.Encoding.Default;
                MailMsg.To.Add(ToEmail);
                MailMsg.Priority = System.Net.Mail.MailPriority.High;
                MailMsg.Subject = "Subject - Window Service";
                MailMsg.Body = strBody;
                MailMsg.IsBodyHtml = true;
                System.Net.Mail.AlternateView HTMLView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(strBody, HTMLType);

                smtpClient.Send(MailMsg);
                WriteErrorLog("Mail sent successfully!");
      }
      catch (Exception ex)
      {
                WriteErrorLog(ex.InnerException.Message);
                throw;
      }
}

STEP 4 : 

After that, Now go to in your main "Service1.cs" class file (Code view), and add the following namespace and methods inside the class

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Configuration;
using System.Timers;

 private System.Timers.Timer timer1;
 private string timeString;
 public int getCallType;

/////////////////////////////////////////////////////////////////////
 public Service1()
 {
      InitializeComponent();
      int strTime = Convert.ToInt32(ConfigurationManager.AppSettings["callDuration"]);
      getCallType = Convert.ToInt32(ConfigurationManager.AppSettings["CallType"]);
      if (getCallType == 1)
      {
           timer1 = new System.Timers.Timer();
           double inter = (double)GetNextInterval();
           timer1.Interval = inter;
           timer1.Elapsed += new ElapsedEventHandler(ServiceTimer_Tick);
      }
      else
      {
           timer1 = new System.Timers.Timer();
           timer1.Interval = strTime * 1000;
           timer1.Elapsed += new ElapsedEventHandler(ServiceTimer_Tick);
      }
 }

/////////////////////////////////////////////////////////////////////
 protected override void OnStart(string[] args)
 {
      timer1.AutoReset = true;
      timer1.Enabled = true;
      SendMailService.WriteErrorLog("Service started");
 }

/////////////////////////////////////////////////////////////////////
 protected override void OnStop()
 {
      timer1.AutoReset = false;
      timer1.Enabled = false;
      SendMailService.WriteErrorLog("Service stopped");
 }

/////////////////////////////////////////////////////////////////////
 private double GetNextInterval()
 {
      timeString = ConfigurationManager.AppSettings["StartTime"];
      DateTime t = DateTime.Parse(timeString);
      TimeSpan ts = new TimeSpan();
      int x;
      ts = t - System.DateTime.Now;
      if (ts.TotalMilliseconds < 0)
      {
           ts = t.AddDays(1) - System.DateTime.Now;//Here you can increase the timer interval based on your requirments.   
      }
      return ts.TotalMilliseconds;
 }

/////////////////////////////////////////////////////////////////////
 private void SetTimer()
 {
      try
      {
           double inter = (double)GetNextInterval();
           timer1.Interval = inter;
           timer1.Start();
      }
      catch (Exception ex)
      {
      }
 }

/////////////////////////////////////////////////////////////////////
 private void ServiceTimer_Tick(object sender, System.Timers.ElapsedEventArgs e)
 {
      string Msg = "Hi ! This is DailyMailSchedulerService mail.";//whatever msg u want to send write here.  
      
      SendMailService.SendEmail("to_email_address@dmain.com", "Subject", Msg);

      if (getCallType == 1)
      {
           timer1.Stop();
           System.Threading.Thread.Sleep(1000000);
           SetTimer();
      }
 }

STEP 5 : 

     Now your windows service is created, but its not done yet. We need to add ProjectInstaller in your project to register service in system, when we install it. To do this right click on design view of your Service1.cs file and select Add Installer option. This will create new file inside your project called "ProjectInstaller.cs". 

     Open ProjectInstaller.cs file. In this file there you can see two types of installer, serviceInstaller1 and serviceProcessInstaller1. Right click on serviceInstaller1 and go to properties and set the ServiceName as same as your Service class file name. In our case, ServiceName will be Service1.

Build the Project now and you will see the .exe file is generated inside bin/Debug folder inside your project source code.

STEP 6 : 

Your Service is ready to be install in the system. to install the service follow the following steps :

  • Go to Start -> Microsoft Visual Studio 2012 -> Visual Studio Tools -> Developer Command Prompt for VS2012. (Right click on it and select Run as administrator)
  • Set path of your Windows Service's .exe file in command prompt (eg. "C:\Users\USER1\Documents\Visual Studio 2012\Projects\WindowsServiceProject1\bin\Debug\").
  • Then run the command : "InstallUtil WindowsServiceProject1.exe". Now your service is successfully installed in your system.
  • Now go to Control Panel -> Administrative Tools -> Services and find the service as name as your windows service (eg. WindowsServiceProject1)


     Windows Service is implemented and installed successfully in your system and will send mail daily itself  at the time which specified ion App.Config file. You can also update this code as whatever you want.
     So as shown in above article, you can also implement your own Windows Services for many other different purpose using ASP.Net and C#.

5 comments:

  1. Nice Article...!!

    ReplyDelete
  2. It doesn't seem to send the mail. the service is started though. pls suggest

    ReplyDelete
  3. Hi Sir, thank you for sharing this code. It did work fine when I ran it with a static receiver's Email ID. Then I just added this bit of code to select some email IDs from database and it stopped working:

    public static void SendEmail()
    {
    SqlConnection con = new SqlConnection("Data Source= DESKTOP-K85D3SJ; Database=dbStudents ; Integrated Security=True");
    SqlCommand cmd = new SqlCommand("select * from students where DATEPART(DAY,BirthDate) = Datepart(day,GETDATE()) and DATEPART(MONTH,BirthDate) = Datepart(MONTH,GETDATE()); ", con);
    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = cmd;
    DataTable dt = new DataTable();
    da.Fill(dt);

    for (int i = 0; i < dt.Rows.Count; i++)
    try
    {
    System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();
    smtpClient.EnableSsl = true;
    smtpClient.Timeout = 200000;
    MailMessage MailMsg = new MailMessage();
    System.Net.Mime.ContentType HTMLType = new System.Net.Mime.ContentType("text/html");

    string strBody = "This is a test mail.";

    MailMsg.BodyEncoding = System.Text.Encoding.Default;
    MailMsg.To.Add(dt.Rows[i]["Email"].ToString());
    MailMsg.Priority = System.Net.Mail.MailPriority.High;
    MailMsg.Subject = "Subject - Window Service";
    MailMsg.Body = strBody;
    MailMsg.IsBodyHtml = true;
    System.Net.Mail.AlternateView HTMLView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(strBody, HTMLType);

    smtpClient.Send(MailMsg);
    WriteErrorLog("Mail sent successfully!");

    }
    catch
    {
    WriteErrorLog("Mail sending Failed...");
    }
    }

    The log file is showing no success or failure message. Please Guide me how to get it right.
    Shall be thankful.

    ReplyDelete