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:
- <configuration>
- <appSettings>
- <add key="StartTime" value="03:50 PM " />
- <add key="callDuration" value="2" />
- <add key="CallType" value="1" />
- <add key="FromMail" value="[email protected]" />
- <add key="Password" value="your_email_id_password" />
- <add key="Host" value="smtp.gmail.com" />
- </appSettings>
- <system.net>
- <mailSettings>
- <smtp from="[email protected]">
- <network host="smtp.gmail.com" userName="[email protected]" password="your_email_id_password" enableSsl="true" port="587" />
- </smtp>
- </mailSettings>
- </system.net>
- </configuration>
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;
- namespace WindowsServiceProject1
- {
- class SendMailService
- {
- // 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;
- }
- }
- }
- }
- 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;
- namespace WindowsServiceProject1
- {
- public partial class TestService : ServiceBase
- {
- private System.Timers.Timer timer1;
- private string timeString;
- public int getCallType;
- /////////////////////////////////////////////////////////////////////
- public TestService()
- {
- InitializeComponent();
- int strTime = Convert.ToInt32(ConfigurationSettings.AppSettings["callDuration"]);
- getCallType = Convert.ToInt32(ConfigurationSettings.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 = ConfigurationSettings.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("[email protected]", "Subject", Msg);
- if (getCallType == 1)
- {
- timer1.Stop();
- System.Threading.Thread.Sleep(1000000);
- SetTimer();
- }
- }
- }
- }
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#.

Aleksa GrbicPosted Aug 18, 2023, 8:13 AM
How to modify to sent email every 1 minutes?
Purwanto Ali SastraPosted Feb 21, 2020, 2:41 AM
For my case it just send 1 time in day 1, in day 2 and next it's not sending email
Siddharth GuptaPosted Oct 14, 2018, 5:54 AM
Hello sir . i ran the code and in the services when i start the service, there is an error 5 : access is denied error.. please tell me how to fix it.
Patel SoniyaPosted May 28, 2018, 7:03 AM
Developer Command Prompt Open As Run As administrator
ashok hPosted May 25, 2018, 11:54 AM
The Rollback phase completed successfully. The transacted install has completed. The installation failed, and the rollback has been performed. i am getting this error, i checked log file but says service started and stopped
Patel SoniyaPosted Dec 28, 2017, 5:23 AM
Can you help me set 4 hour timing in mail plz...........
Patel SoniyaPosted Dec 28, 2017, 5:22 AM
Hello sir nice artical it 's work fine
Ǻdñâň AbbẵŝPosted Nov 6, 2017, 3:05 AM
Thanks for sharing . how can we send email to multiple contacts???
ros mohPosted Oct 27, 2017, 9:07 AM
I says it ran, I am still waiting for 1st email to receive, fingers crossed. Any other good examples using jquery
Karthick sekarPosted Jun 3, 2017, 3:22 AM
Service is running successfully but i did not receive mail
Bahubali GanePosted Jun 2, 2017, 3:11 AM
Is it possible to do by using wcf web secvice?????
Ayushee MittalPosted Mar 16, 2017, 6:37 AM
It doesn't seem to send the mail. the service is started though. pls suggest
Satyaprakash SamantarayPosted Oct 24, 2016, 3:03 PM
Add images with your articles for viewer better understanding
hammad ur rehmanPosted Feb 19, 2016, 1:24 AM
I did work on Window Service for auto generating email to outlook, After worked and installed on services , Email is not generating auto..
hammad ur rehmanPosted Feb 19, 2016, 1:24 AM
I did work on Window Service for auto generating email to outlook, After worked and installed on services , Email is generating auto..
Zeeshan AzimPosted Nov 2, 2015, 5:30 PM
Well Done Bro !
madhavi lathaPosted Oct 26, 2015, 8:58 AM
Service is not Running after installation,Its showing the following error in developer command Promt"The service is not responding to the control fuction.More help is available by typing NET HELPMSG 2186 "
Santhakumar MunuswamyPosted Oct 18, 2015, 5:20 AM
Good one
Jignesh RavalPosted Oct 8, 2015, 6:44 AM
Thanks to everyone...!!
RakeshPosted Oct 8, 2015, 1:29 AM
Good share
Ankit BansalPosted Oct 8, 2015, 12:51 AM
nice one..
Humayun Kabir MamunPosted Oct 8, 2015, 12:13 AM
Nice...
Nilesh JadavPosted Oct 7, 2015, 9:45 PM
Nice one sir
Muhammad Aqib ShehzadPosted Oct 7, 2015, 3:15 PM
nice
Vinodh NarayananPosted Oct 7, 2015, 1:20 PM
Nice thanks for sharing
Sujeet SumanPosted Oct 7, 2015, 11:42 AM
Nice Article................
Rajeesh MenothPosted Oct 7, 2015, 11:18 AM
Nice Share, Welcome to C# Corner Community :)...