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>
Step 4
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);
- }
- }
Note: For using the ConfigurationManager add the reference first and then use the class.
- 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;
- }
- return ts.TotalMilliseconds;
- }
- private void SetTimer()
- {
- try
- {
- double inter = (double)GetNextInterval();
- timer1.Interval = inter;
- timer1.Start();
- }
- catch (Exception ex)
- {
- }
- }
In the timer OnStart() function first write a message to the log that the service has been started and when the service stops write to the log that the service has stopped.
- 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");
- }
Here I am creating a class ServiceLog that contains the followings function.
-
-
-
-
- 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
- {
- }
- }
-
-
-
-
- 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 class also contains a function that will send email to the mail id passed by its arguments.
- #region Send Email Code Function
-
-
-
-
-
-
-
-
- public static void SendEmail(String ToEmail, string cc, string bcc, String Subj, string Message)
- {
-
-
- string HostAdd = ConfigurationManager.AppSettings["Host"].ToString();
- string FromEmailid = ConfigurationManager.AppSettings["FromMail"].ToString();
- string Pass = ConfigurationManager.AppSettings["Password"].ToString();
-
-
- MailMessage mailMessage = new MailMessage();
- mailMessage.From = new MailAddress(FromEmailid);
- mailMessage.Subject = Subj;
- mailMessage.Body = Message;
- mailMessage.IsBodyHtml = true;
-
- string[] ToMuliId = ToEmail.Split(',');
- foreach (string ToEMailId in ToMuliId)
- {
- mailMessage.To.Add(new MailAddress(ToEMailId));
- }
-
-
- string[] CCId = cc.Split(',');
-
- foreach (string CCEmail in CCId)
- {
- mailMessage.CC.Add(new MailAddress(CCEmail));
- }
-
- string[] bccid = bcc.Split(',');
-
- foreach (string bccEmailId in bccid)
- {
- mailMessage.Bcc.Add(new MailAddress(bccEmailId));
- }
- SmtpClient smtp = new SmtpClient();
- smtp.Host = HostAdd;
-
-
-
- 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);
- }
-
- #endregion
Step 5
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.";
-
- 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();
- }
- }
Step 6
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.
Debug Window Service
- 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.