Introduction
In this article I am explaining how to create a Windows Service to schedule daily mail at a specified time. Scheduling email and sending the email is a basic requirement of any project.
Step 1
Open Visual Studio and create a new project. Under Windows Desktop select Windows Service and provide a proper name and click on the OK button.
Step 2
Rename the service1 class to a proper name. In this case I am using mail service. Click on “Click here to switch to code view”.
Step 3
Add some app settings in the app.config file as in the following:
- <appSettings>
- <add key="StartTime" value="08:33 PM "/>
- <add key="callDuration" value="2"/>
- <add key="CallType" value="1"/>
- <add key="FromMail" value="****"/>
- <add key="Password" value="****"/>
- <add key="Host" value="smtpout.secureserver.net"/>
- </appSettings>
In the MailService class write the following function.
- public Scheduler()
- {
- 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);
- }
- }
- 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)
- {
- }
- }
- protected override void OnStart(string[] args)
- {
- timer1.AutoReset = true;
- timer1.Enabled = true;
- ServiceLog.WriteErrorLog("Daily Reporting service started");
- }
- protected override void OnStop()
- {
- timer1.AutoReset = false;
- timer1.Enabled = false;
- ServiceLog.WriteErrorLog("Daily Reporting service stopped");
- }
- /// <summary>
- /// This function write log to LogFile.text when some error occurs.
- /// </summary>
- /// <param name="ex"></param>
- 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
- {
- }
- }
- /// <summary>
- /// this function write Message to log file.
- /// </summary>
- /// <param name="Message"></param>
- 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
- {
- }
- }
- #region Send Email Code Function
- /// <summary>
- /// Send Email with cc bcc with given subject and message.
- /// </summary>
- /// <param name="ToEmail"></param>
- /// <param name="cc"></param>
- /// <param name="bcc"></param>
- /// <param name="Subj"></param>
- /// <param name="Message"></param>
- public static void SendEmail(String ToEmail, string cc, string bcc, String Subj, string Message)
- {
- //Reading sender Email credential from web.config file
- string HostAdd = ConfigurationManager.AppSettings["Host"].ToString();
- string FromEmailid = ConfigurationManager.AppSettings["FromMail"].ToString();
- string Pass = ConfigurationManager.AppSettings["Password"].ToString();
- //creating the object of MailMessage
- MailMessage mailMessage = new MailMessage();
- mailMessage.From = new MailAddress(FromEmailid); //From Email Id
- mailMessage.Subject = Subj; //Subject of Email
- mailMessage.Body = Message; //body or message of Email
- mailMessage.IsBodyHtml = true;
- string[] ToMuliId = ToEmail.Split(',');
- foreach (string ToEMailId in ToMuliId)
- {
- mailMessage.To.Add(new MailAddress(ToEMailId)); //adding multiple TO Email Id
- }
- string[] CCId = cc.Split(',');
- foreach (string CCEmail in CCId)
- {
- mailMessage.CC.Add(new MailAddress(CCEmail)); //Adding Multiple CC email Id
- }
- string[] bccid = bcc.Split(',');
- foreach (string bccEmailId in bccid)
- {
- mailMessage.Bcc.Add(new MailAddress(bccEmailId)); //Adding Multiple BCC email Id
- }
- SmtpClient smtp = new SmtpClient(); // creating object of smptpclient
- smtp.Host = HostAdd; //host of emailaddress for example smtp.gmail.com etc
- //network and security related credentials
- smtp.EnableSsl = false;
- NetworkCredential NetworkCred = new NetworkCredential();
- NetworkCred.UserName = mailMessage.From.Address;
- NetworkCred.Password = Pass;
- smtp.UseDefaultCredentials = true;
- smtp.Credentials = NetworkCred;
- smtp.Port = 3535;
- smtp.Send(mailMessage); //sending Email
- }
- #endregion
Now inside the MailService class write a ServiceTimer_Tick() function. This function is mainly used for the task done by this Window Service when the timer tic reaches the time specified in the app.config file. You can change your code based on your requirements.
- 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.
- // Here you can write the
- ServiceLog.SendEmail("[email protected]", "[email protected]", "[email protected]", "Daily Report of DailyMailSchedulerService on " + DateTime.Now.ToString("dd-MMM-yyyy"), Msg);
- if (getCallType == 1)
- {
- timer1.Stop();
- System.Threading.Thread.Sleep(1000000);
- SetTimer();
- }
- }
Now your Windows Service is ready. Compile this and use the following procedure to install and use this Windows Service.
Install Windows Service.
- Go to "Start" >> "All Programs" >> "Microsoft Visual Studio 2012" >> "Visual Studio Tools" . Click "Developer Command Prompt for VS2012".
Type the following command:
cd <physical location of your DailyMailSchedulerService.exe file>
In my case it is:
cd D:\Dot Net Program\DailyMailSchedulerService\DailyMailSchedulerService\bin\Debug
- Type the following command:
InstallUtil.exe “DailyMailSchedulerService.exe”
And press Enter.
Now go to Services and find the services of your project name and start that service. You will then start finding the mail every day at 08:00 PM.
- Build the Solution.
- Start your Service.
- While your Service is starting, go to --> Debug --> Attach Process.
- Make sure "Show Process from all users" and "Show Process in all sessions" are checked.
- Find your "" in the list and click "Attach".
- You should now be at the breakpoint you inserted.
Summary
In this illustration we learned about Windows Service and sending mail daily by using that service. This may be helpful somehow when scheduling something based on your requirements. Please provide your valuable comments about this article.

Raul LunaPosted Sep 9, 2023, 2:55 PM
Please send me the code to my email to [email protected]. thanks in advance
Rizwan khanPosted Jun 24, 2021, 12:14 PM
Email is not sending in window service "Unable to connect to the remote server" while in web project its working fine. need your help thanks. Any body : reply [email protected]
David FintenPosted Jun 7, 2021, 2:38 AM
Please send me the code to my email to [email protected]. thanks
wadldPosted Mar 23, 2021, 2:30 PM
Please send me the code to my email [email protected]
nakshatra sawantPosted Mar 15, 2021, 10:59 AM
Please send me the code to my mail [email protected]
cnttcd aPosted Mar 9, 2021, 2:52 AM
Please send the code to mail sir [email protected]
faiz ahamedPosted Oct 5, 2020, 2:11 AM
Please send the code to mail sir [email protected]
Ripon GogiPosted Mar 31, 2020, 5:17 AM
Please send me the code at my mail- [email protected]
Sachin AherPosted Aug 12, 2019, 7:50 AM
Please send me the code to my mail sir. [email protected]
Thys SteenkampPosted Mar 25, 2019, 5:04 AM
Can i please get the code for this? [email protected]
sayliPosted Mar 7, 2019, 12:50 AM
I want to run job on Hourly, daily or weekly basis depending on the choice of a user which I ccan get form windows application. If hourly, options = Every X hours. If daily, options = Time of day.If weekly, options = Day of week and time of day
Sunil AcharyaPosted Dec 20, 2018, 11:41 PM
Manish, Can we set dependencies on this to check the other service are working or not or force to start them? like if LAN Connection is not there then it force to start or display some message for the same.
jamshed alamPosted May 3, 2018, 5:49 AM
Very nice, clear and useful article
Fatih KARAKAŞPosted Feb 19, 2018, 8:13 AM
I want to zip file this program with source code. [email protected]
changhai gohPosted Feb 12, 2018, 1:11 AM
Please send me the code to my mail [email protected]
Dhanush NairPosted Jan 31, 2018, 3:26 AM
Please send me the code to my mail sir. [email protected]
Chandan KumarPosted Jan 25, 2018, 6:33 AM
On my email [email protected]
Chandan KumarPosted Jan 25, 2018, 6:32 AM
Ok Thank You So much sir, would you please send me the zip file of this program
Shivshanker CheralPosted Dec 20, 2016, 9:19 AM
It has two methods with the same name "WriteErrorLog"
Mohamed FouadPosted Sep 4, 2016, 8:11 AM
Not working
vinayak ghantiPosted Jun 26, 2016, 8:19 AM
hi Manish nice article i want to know how we can host this service in server like how we host a website i ? or do we need VPS please let me know
Wajeed AliPosted May 11, 2016, 10:05 AM
Nice Article
Abhijit DasPosted Mar 18, 2016, 9:20 AM
waoow, its a nice example
sameer skPosted Mar 4, 2016, 5:18 AM
here is my mail id [email protected]
sameer skPosted Mar 4, 2016, 5:18 AM
need to study this project ,Manish sir can you please send me a build exe file for this program
bhimani sambaPosted Sep 2, 2015, 7:20 AM
service is running but not receving mail message so once check and update immediately
bhimani sambaPosted Sep 2, 2015, 7:19 AM
iam testing this article,but not receving mail message.so once check and update immediately
bhimani sambaPosted Sep 2, 2015, 7:12 AM
This article is not working .. please check once
Rajeesh MenothPosted Jul 28, 2015, 6:52 AM
Good Article Sir
Saber ShaikhPosted Jul 14, 2015, 8:35 AM
nice
Polyana PolanaPosted Jun 17, 2015, 4:33 AM
Hi Manish, this is a nice article. Thank you for submitting it. I have a few questions. The method Scheduler is a constructor, where is it coming from? And there are variables without type, like timer1, getCallType, are they defined somewhere else? I am a bit new so maybe I am missing the point.
Nick DemariPosted May 29, 2015, 1:03 PM
Can i have the source code?
hussain baigPosted Mar 16, 2015, 4:18 AM
Nice article. I was looking same kind of requirement, got here.
Gowtham RajamanickamPosted Mar 13, 2015, 5:24 AM
Good article !
Manish Kumar ChoudharyPosted Feb 17, 2015, 7:40 AM
Thanks for reading this article Sumit Jolly sir. yes we can achieve email scheduling using sql server job scheduling also.
Guest UserPosted Feb 17, 2015, 7:37 AM
I read this article now. There is another way to achieve email scheduler is via Sql Server db job. It has scheduler built-in, so its an alternative to windows task scheduler.
Manish Kumar ChoudharyPosted Feb 17, 2015, 7:02 AM
Harpreet Singh sir thanks for reading and posting your valuable comments.
Manish Kumar ChoudharyPosted Feb 17, 2015, 7:01 AM
Thanks Piyush Pansuriya. Yes possible store 10 different message and email id in list and then send.
Harpreet SinghPosted Feb 17, 2015, 6:55 AM
another interesting article....very nice
Piyush PansuriyaPosted Feb 17, 2015, 6:55 AM
This is nice but, If I want to send 10 different msg to 10 Diff. email at a same time. is it possible?
Manish Kumar ChoudharyPosted Jan 11, 2015, 11:03 PM
Thanks burak horozoglu sir.
burak horozogluPosted Jan 11, 2015, 9:54 AM
good and working sample. Thanks
Manish Kumar ChoudharyPosted Dec 27, 2014, 11:44 AM
Thanks KP Singh Chundawat sir....
K P Singh ChundawatPosted Dec 27, 2014, 6:59 AM
Nice Article .. Manish Kumar Choudhary sir
ratnesh kumarPosted Dec 5, 2014, 2:23 AM
sir,could you please tell me , what is the use of calltype and callduration in app.config()
RahulPosted Nov 17, 2014, 10:24 AM
Manish, but i have worked on application with send file and email through day and likewise, believe me you can achieve all the similar requirement with window task Scheduler. No need to write a new service as the task scheduler service does the same also it provide logging and other feature. You can you use Task scheduler unless there is some dependent scheduling and few more limitations.
Vithal WadjePosted Nov 17, 2014, 7:27 AM
good one,what is difference between creating scheduler using console application and windows service
RahulPosted Nov 17, 2014, 5:21 AM
It’s better to user Window Task Scheduler to schedule the exe for sending the email. Task scheduler have a window service running in every system.