Create Windows Service To Send Email Daily Using ASP.NET And C#

Step 1: Create Windows Service Project in Microsoft Visual Studio 2012 and give project name "WindowsServiceProject1".

Step 2: Now update your App.Config file as in the following code snippet:

  1. <configuration>  
  2.     <appSettings>  
  3.         <add key="StartTime" value="03:50 PM " />  
  4.         <add key="callDuration" value="2" />  
  5.         <add key="CallType" value="1" />  
  6.         <add key="FromMail" value="[email protected]" />  
  7.         <add key="Password" value="your_email_id_password" />  
  8.         <add key="Host" value="smtp.gmail.com" />  
  9.     </appSettings>  
  10.     <system.net>  
  11.         <mailSettings>  
  12.             <smtp from="[email protected]">  
  13.                 <network host="smtp.gmail.com" userName="[email protected]" password="your_email_id_password" enableSsl="true" port="587" />  
  14.             </smtp>  
  15.         </mailSettings>  
  16.     </system.net>  
  17. </configuration>  
In this configuration settings, we use gmail email id to send email, 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.
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Configuration;    
  4. using System.IO;    
  5. using System.Linq;    
  6. using System.Net;    
  7. using System.Net.Mail;    
  8. using System.Text;    
  9.     
  10. namespace WindowsServiceProject1    
  11. {    
  12.     class SendMailService    
  13.     {    
  14.         // This function write log to LogFile.text when some error occurs.      
  15.         public static void WriteErrorLog(Exception ex)    
  16.         {    
  17.             StreamWriter sw = null;    
  18.             try    
  19.             {    
  20.                 sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt"true);    
  21.                 sw.WriteLine(DateTime.Now.ToString() + ": " + ex.Source.ToString().Trim() + "; " + ex.Message.ToString().Trim());    
  22.                 sw.Flush();    
  23.                 sw.Close();    
  24.             }    
  25.             catch    
  26.             {    
  27.             }    
  28.         }    
  29.         // This function write Message to log file.    
  30.         public static void WriteErrorLog(string Message)    
  31.         {    
  32.             StreamWriter sw = null;    
  33.             try    
  34.             {    
  35.                 sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt"true);    
  36.                 sw.WriteLine(DateTime.Now.ToString() + ": " + Message);    
  37.                 sw.Flush();    
  38.                 sw.Close();    
  39.             }    
  40.             catch    
  41.             {    
  42.             }    
  43.         }    
  44.         // This function contains the logic to send mail.    
  45.         public static void SendEmail(String ToEmail, String Subj, string Message)    
  46.         {    
  47.             try    
  48.             {    
  49.                 System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient();    
  50.                 smtpClient.EnableSsl = true;    
  51.                 smtpClient.Timeout = 200000;    
  52.                 MailMessage MailMsg = new MailMessage();    
  53.                 System.Net.Mime.ContentType HTMLType = new System.Net.Mime.ContentType("text/html");    
  54.     
  55.                 string strBody = "This is a test mail.";    
  56.     
  57.                 MailMsg.BodyEncoding = System.Text.Encoding.Default;    
  58.                 MailMsg.To.Add(ToEmail);    
  59.                 MailMsg.Priority = System.Net.Mail.MailPriority.High;    
  60.                 MailMsg.Subject = "Subject - Window Service";    
  61.                 MailMsg.Body = strBody;    
  62.                 MailMsg.IsBodyHtml = true;    
  63.                 System.Net.Mail.AlternateView HTMLView = System.Net.Mail.AlternateView.CreateAlternateViewFromString(strBody, HTMLType);    
  64.     
  65.                 smtpClient.Send(MailMsg);    
  66.                 WriteErrorLog("Mail sent successfully!");    
  67.             }    
  68.             catch (Exception ex)    
  69.             {    
  70.                 WriteErrorLog(ex.InnerException.Message);    
  71.                 throw;    
  72.             }    
  73.         }    
  74.     }    
  75. }    
Step 4: After that go to your main "TestService.cs" class file (Code view), and add the following namespace and methods inside the class.
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.ComponentModel;    
  4. using System.Data;    
  5. using System.Diagnostics;    
  6. using System.Linq;    
  7. using System.ServiceProcess;    
  8. using System.Text;    
  9. using System.Configuration;    
  10. using System.Timers;    
  11.     
  12. namespace WindowsServiceProject1    
  13. {    
  14.     public partial class TestService : ServiceBase    
  15.     {    
  16.         private System.Timers.Timer timer1;    
  17.         private string timeString;    
  18.         public int getCallType;    
  19.     
  20.         /////////////////////////////////////////////////////////////////////    
  21.         public TestService()    
  22.         {    
  23.             InitializeComponent();    
  24.             int strTime = Convert.ToInt32(ConfigurationSettings.AppSettings["callDuration"]);    
  25.             getCallType = Convert.ToInt32(ConfigurationSettings.AppSettings["CallType"]);    
  26.             if (getCallType == 1)    
  27.             {    
  28.                 timer1 = new System.Timers.Timer();    
  29.                 double inter = (double)GetNextInterval();    
  30.                 timer1.Interval = inter;    
  31.                 timer1.Elapsed += new ElapsedEventHandler(ServiceTimer_Tick);    
  32.             }    
  33.             else    
  34.             {    
  35.                 timer1 = new System.Timers.Timer();    
  36.                 timer1.Interval = strTime * 1000;    
  37.                 timer1.Elapsed += new ElapsedEventHandler(ServiceTimer_Tick);    
  38.             }    
  39.         }    
  40.     
  41.         /////////////////////////////////////////////////////////////////////    
  42.         protected override void OnStart(string[] args)    
  43.         {    
  44.             timer1.AutoReset = true;    
  45.             timer1.Enabled = true;    
  46.             SendMailService.WriteErrorLog("Service started");    
  47.         }    
  48.     
  49.         /////////////////////////////////////////////////////////////////////    
  50.         protected override void OnStop()    
  51.         {    
  52.             timer1.AutoReset = false;    
  53.             timer1.Enabled = false;    
  54.             SendMailService.WriteErrorLog("Service stopped");    
  55.         }    
  56.     
  57.         /////////////////////////////////////////////////////////////////////    
  58.         private double GetNextInterval()    
  59.         {    
  60.             timeString = ConfigurationSettings.AppSettings["StartTime"];    
  61.             DateTime t = DateTime.Parse(timeString);    
  62.             TimeSpan ts = new TimeSpan();    
  63.             int x;    
  64.             ts = t - System.DateTime.Now;    
  65.             if (ts.TotalMilliseconds < 0)    
  66.             {    
  67.                 ts = t.AddDays(1) - System.DateTime.Now;//Here you can increase the timer interval based on your requirments.       
  68.             }    
  69.             return ts.TotalMilliseconds;    
  70.         }    
  71.     
  72.         /////////////////////////////////////////////////////////////////////    
  73.         private void SetTimer()    
  74.         {    
  75.             try    
  76.             {    
  77.                 double inter = (double)GetNextInterval();    
  78.                 timer1.Interval = inter;    
  79.                 timer1.Start();    
  80.             }    
  81.             catch (Exception ex)    
  82.             {    
  83.             }    
  84.         }    
  85.     
  86.         /////////////////////////////////////////////////////////////////////    
  87.         private void ServiceTimer_Tick(object sender, System.Timers.ElapsedEventArgs e)    
  88.         {    
  89.             string Msg = "Hi ! This is DailyMailSchedulerService mail.";//whatever msg u want to send write here.      
  90.     
  91.             SendMailService.SendEmail("[email protected]""Subject", Msg);    
  92.     
  93.             if (getCallType == 1)    
  94.             {    
  95.                 timer1.Stop();    
  96.                 System.Threading.Thread.Sleep(1000000);    
  97.                 SetTimer();    
  98.             }    
  99.         }    
  100.     }    
  101. }    
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 TestService.cs file and select Add Installer option. This will create a 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 TestService.

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

Step 6: Your Service is ready to be installed in the system. To install the service here are the steps:

 

  • Go to Start, Microsoft Visual Studio 2012, Visual Studio Tools, then 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 (e.g. "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, then Services and find the service name as your windows service (eg. TestService).

Windows Service is implemented and installed successfully in your system and will send mail daily itself at the time which specified 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#.

Up Next
    Ebook Download
    View all
    Learn
    View all