This tutorial is in continuation to the creation of a C# Windows Service to send Automated Emails asynchronously. Kindly go through the following link to get started with the PART – I.
================================================================================================
Sending Automated Emails asynchronously using a C# Windows Service in conjunction with Database Email records PART – I
================================================================================================
NOTE :-
- This part of the tutorial is especially focused on the Windows Service creation, configuration and installation. The concepts (precisely the database and class library) used in this part is already created and explained in the Part 1 of the tutorial.
- Apart from the continuation from Part –1, this Part can actually be implemented separately according to the requirement. At the same time, this part of the tutorial can be implemented with variety of concepts like XML, EF, LINQ etc. So it is typically based on the requirement to make different pieces fall in place.
In this part of the tutorial, we first create a Windows Service Project, then implement a Service called – ‘BirthdayEmailService’. Then we add a reference to our previously created Class Library – ‘EmailComponent’. We code BirthdayEmailService using Timer to perform the email sending task for every hour. Then we incorporate the Installer classes for the purpose of installation. Finally a Setup and Deployment Project is created for the Service. Finally the complete Solution is build and the exe file is generated which is ready enough to get installed.
IMPORTANT – The logic in the using the Timer is to send emails in particular intervals of time. The timer interval is set to 60mins, and it is set to that value solely for demonstration purpose. According to the written logic, emails will be send only for the first time elapsed event of a particular date, so that the repetition of sending emails to the same customers can be avoided. Always remember, logic in the service Time Event can be modified according to ones requirement.
================================================================================================
BirthdayEmailService Project
This section narrates how to create a Windows Project. It also discuss how to prepare the project according to our requirement (say adding references etc).
================================================================================================
Let’s get started with the creation of Windows Service.
- Open VS 2010
- File -> New -> Project
- Select ‘Visual C#’ -> Windows -> Windows Service Template -> Give Name ‘BirthdayEmailSevice’
- Delete the default Service1.cs
To access Database i.e., CustomerDB, we include a app.config file which in this case hold the data corresponding to the database connectivity ( like connection string etc).
To add app.config file -
- Right click ‘BirthdayEmailService’ in the solution explorer –> Select ‘Add New Item’.
- Select ‘Visual C#’ -> Select Application Configuration File Template -> Click ADD.
To make the ConfigurationManager ( which is used to access config file settings in the code), we add reference to System.Configuration.dll to the project (right click Project ‘BirthdayEmailService’ -> Select Add Reference -> from .Net tab, Select System.Configuaration -> click ADD).
Put the following code in the created app.config file –
<?xml version="1.0" encoding="utf-8" ?> <configuration> <connectionStrings> <add name="CustomerDBConnectionString" connectionString="Data Source=RAMILU-PC\SQLEXPRESS;Initial Catalog=CustomerDB;Integrated Security=True;Pooling=False" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration>
Now let’s add a Service to the project –
- Right Click ‘BirthdayEmailService’ in the Solution Explorer –> Select ‘Add New Item’.
- Select ‘Visual C# Items’ -> Select Windows Service Template -> Give name – ‘BirthdayEmailService.cs’.
- Click ADD.
To Code against the EmailComponent (which we created earlier), we got to add reference of it to our service.
- Right Click ‘References’ of BirthdayEmailService –> Select ‘Add Reference’.
- Select ‘Browse’ tab -> Navigate to the ‘EmaiComponent’ project folder -> Select the EmailComponent.dll in the bin/Debug folder of ‘EmailComponent’ project. (NOTE: Before adding the reference, build the EmailComponent Project so that it would be up to date.)
- Click OK.
One last thing which is left behind is to change the Entry point of the application -
- Open Program.cs of the newly created service.
- Replace the Main() function with the following one –
static void Main() { ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new BirthdayEmailService() }; ServiceBase.Run(ServicesToRun); }
Now, Writing code to BirthdayEmailService.cs –
- Open BirthdayEmailService.cs in designer mode in VS 2010.
- Drag and drop an EventLog component and Timer component (Please do not add this Timer component, I am adding this component from C# – Update : 1/16/2012) from the ToolBox on to the designer.
- Change their names to eventLogEmail and scheduleTimer (check (2), please do not add Timer component, I am adding this from C# – Update : 1/16/2012).
- EventLog is used to log the activities of the service, and timer is used to make the service run at particular intervals of time.
- Right click anywhere in the designer surface -> Select -> View Code.
Write the following code –
- Change the Settings/Properties as per your own settings. Especially the Network Credentials and Username.
- In the code, we first get the email id’s (in DataSet) of all the customers who are celebrating their birthday on that particular day, then we iterate through the through the DataSet and call the SendEmailAsync() method of EmailComponent dll. SendEmailAsync() method then process asynchronously and sends back the result.
- We set the From Email, To Email, subject, Message Body etc. properties in this routine and pass the same values to the EmailComponent dll for further processing.
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.Timers; using System.Configuration; using EmailComponent; namespace BirthdayEmailService { partial class BirthdayEmailService : ServiceBase { private Timer scheduleTimer = null; private DateTime lastRun; private bool flag; public BirthdayEmailService() { InitializeComponent(); if (!System.Diagnostics.EventLog.SourceExists("EmailSource")) { System.Diagnostics.EventLog.CreateEventSource("EmailSource", "EmailLog"); } eventLogEmail.Source = "EmailSource"; eventLogEmail.Log = "EmailLog"; scheduleTimer = new Timer(); scheduleTimer.Interval = 1 * 5 * 60 * 1000; scheduleTimer.Elapsed += new ElapsedEventHandler(scheduleTimer_Elapsed); } protected override void OnStart(string[] args) { flag = true; lastRun = DateTime.Now; scheduleTimer.Start(); eventLogEmail.WriteEntry("Started"); } protected void scheduleTimer_Elapsed(object sender, ElapsedEventArgs e) { if (flag == true) { ServiceEmailMethod(); lastRun = DateTime.Now; flag = false; } else if (flag == false) { if (lastRun.Date < DateTime.Now.Date) { ServiceEmailMethod(); } } } private void ServiceEmailMethod() { eventLogEmail.WriteEntry("In Sending Email Method"); EmailComponent.GetEmailIdsFromDB getEmails = new EmailComponent.GetEmailIdsFromDB(); getEmails.connectionString = ConfigurationManager.ConnectionStrings["CustomerDBConnectionString"].ConnectionString; getEmails.storedProcName = "GetBirthdayBuddiesEmails"; System.Data.DataSet ds = getEmails.GetMailIds(); EmailComponent.Email email = new EmailComponent.Email(); email.fromEmail = "example@gmail.com"; email.fromName = "example Name"; email.subject = "Birthday Wishes"; email.smtpServer = "smtp.gmail.com"; email.smtpCredentials = new System.Net.NetworkCredential("example@gmail.com", "example password"); foreach (System.Data.DataRow dr in ds.Tables[0].Rows) { email.messageBody = "<h4>Hello " + dr["CustomerName"].ToString() + "</h4><br/><h3>We Wish you a very Happy" + "Birthday to You!!! Have a bash...</h3><br/><h4>Thank you.</h4>"; bool result = email.SendEmailAsync(dr["CustomerEmail"].ToString(), dr["CustomerName"].ToString()); if (result == true) { eventLogEmail.WriteEntry("Message Sent SUCCESS to - " + dr["CustomerEmail"].ToString() + " - " + dr["CustomerName"].ToString()); } else { eventLogEmail.WriteEntry("Message Sent FAILED to - " + dr["CustomerEmail"].ToString() + " - " + dr["CustomerName"].ToString()); } } } protected override void OnStop() { scheduleTimer.Stop(); eventLogEmail.WriteEntry("Stopped"); } protected override void OnPause() { scheduleTimer.Stop(); eventLogEmail.WriteEntry("Paused"); } protected override void OnContinue() { scheduleTimer.Start(); ; eventLogEmail.WriteEntry("Continuing"); } protected override void OnShutdown() { scheduleTimer.Stop(); eventLogEmail.WriteEntry("ShutDowned"); } } }
To install the created Service – We need to add installers, to do that –
- Go to the Designer Pane of the Service (BirthdayEmailService) -> Right Click in the Designer Pane -> Select Add Installer.
Now in Design view for ProjectInstaller, Select serviceInstaller1.
- Set the ServiceName property to BirthdayEmailService. Set the StartType property to Automatic.
- Now Select -> serviceProcessInstaller1 -> set its Account property to LocalSystem. This will cause the service to be installed and to run on a local service account.
This completes the coding part of the Service. Now to install Service, we got to create setup project –
- Right Click Solution -> Add -> New Project
- Other Project Types -> Setup and Deployment -> Visual Studio Installer –> Select ‘Setup’ Project.
- Name – BirthdayEmailServiceSetup -> Click ADD.
To Add Project Output –
- Right Click -> BirthdayEmailServiceSetup (in solution explorer) -> Add -> Project Output
- Select Primary Output (along with Service name in the top DropDownList) -> click OK.
To Add Custom Actions –
- In Solution Explorer, right-click the setup project, Select View, and then click Custom Actions.
- In the Custom Actions editor, right-click the Custom Actions node and click Add Custom Action.
- In the opened Dialog, Double-click the Application Folder in the list to open it, select Primary Output from BirthdayEmailService(Active), and click OK.
The final Stage –
- Right Click the BirthdayEmailService Project in the solutions explorer, and select Set As Startup Project.
- Then build the BirthdayEmailService Project.
- Finally build the BirthdayEmailServiceSetup project too.
The complete Folder structure would be -

On successful build, Navigate to the physical location of the Setup Project (BirthdayEmailServiceSetup) to find the exe file in the Debug Folder. Take the EXE file and install it by double clicking it. On successful install, we can find the service in the Systems Services Window -
- Go to Control Panel –> Administrative Tools –> Services.
We can start the service by right clicking it and select start. Similarly, we can stop it, pause it and continue it. The starting action of the service is only required for initial time, later onwards on shutdown and re-start, service will be automatically started.

To find the EventLog Entries -
- Go to Control Panel –> Administrative Tools –> Event Viewer –> Applications and Services Logs.
There we can find our EmailLog –

EventLog logging Email Send Details – ***I tested the code with 5mins time interval.

Sample Email in the Inbox -

Disclaimer:
All coding and suggestions made in the above discussion is strictly in point of view of the author. It is neither mentioned any where nor even concluded that this is the only possible way to go with, as there will be always a chance for a new approach in achieving the same requirement (in context of programming). The above mentioned code is strictly written and explained for the sake of new comers to C# and ASP.NET world.







Awsome!
It looks very helpfull…but reality come to pictuer only after using it.
However, still i can get some idea from this to use inmy oriject.
sir may i know how it will work in production environment…
How can i upload windows services to production environment?
Regards,
murali
Awsome Work!!
Can you please tell me how can I sent the mail as a high priority mail using my web service……like the one which we are getting in Gmail now a days??
I have completed all the steps but when I am about to build it it shows a error..
Error 1 The type ‘BirthdayEmailService.BirthdayEmailService’ already contains a definition for ‘scheduleTimer’ C:\Documents and Settings\Raja Dutta\My Documents\Visual Studio 2008\Projects\BirthdayEmailSevice\BirthdayEmailSevice\BirthdayEmailService.Designer.cs 46 44 BirthdayEmailSevice
PLEASE HELP ME..URGENTLY…
Rohit –
Please do not add Timer to the BirthdayEmailService.cs Designer Service, just only add EventLog. I forgot to update my article and it caused this havoc situation. I am adding Timer from code rather than in designer service.
I am updating the content now.
Apologies,
Rami.
thanks for this very useful tutorial ! i was working on a similar project and this tutorial really helped me
wonderful step by step any one can understand thanks bro..keep rocking
i get the error some services stops automatically wen not used by other services or programmes…wat i should in this case..pl help…
Error 1 The type ‘BirthdayEmailService.BirthdayEmailService’ already contains a definition for ‘scheduleTimer’
please provide me solve it
Ahmed –
Please do not add Timer to the BirthdayEmailService.cs Designer Service, just only add EventLog. I forgot to update my article and it caused this havoc situation. I am adding Timer from code rather than in designer service.
I am updating the content now.
Apologies,
Rami.
It’s good But While build it is giving one error.
Error 1 The type ‘BirthdayEmailSevice.BirthdayEmailService’ already contains a definition for ‘scheduleTimer’ E:\Dot Net Projects 2011 Dec on holiday\BirthdayEmailSevice\BirthdayEmailSevice\BirthdayEmailService.Designer.cs 46 43 BirthdayEmailSevice
Pankaj –
Please do not add Timer to the BirthdayEmailService.cs Designer Service, just only add EventLog. I forgot to update my article and it caused this havoc situation. I am adding Timer from code rather than in designer service.
I am updating the content now.
Apologies,
Rami.
-> I was sucessfull till “To find the EventLog Entries”
->I was unable to get Success or Failure message in event viewer
->”In Sending Email Method” is displayed in place of Success or Failure message
Sam – Check out your SMTP configuration – Rami.
Email log show success send, but any email goes. have you any solution? thanks
Matt – Check out your SMTP configuration – Rami.
Error : This member(scheduleTimer) is defined more than once
Ambiguity between BirthdayEmailService.BirthdayEmailService.scheduleTimer and BirthdayEmailService.BirthdayEmailService.scheduleTimer
please provide solution asap
Pooja –
Please do not add Timer to the BirthdayEmailService.cs Designer Service, just only add EventLog. I forgot to update my article and it caused this havoc situation. I am adding Timer from code rather than in designer service.
I am updating the content now.
Apologies,
Rami.
Rami,
its really a nice article. very useful for learners.. and can you explain the concepts used .. it will be very very useful to us.. thanks in advance..
rami, i am not able to add the service, while executing with installutil.exe i am getting this error.. what do i do to rectify this..
i am not able to double click and install the exe file created.. please help me..
error msg:
An exception occurred during the Install phase.
System.InvalidOperationException: Cannot open Service Control Manager on compute
r ‘.’. This operation might require other privileges.
The inner exception System.ComponentModel.Win32Exception was thrown with the fol
lowing error message: Access is denied.
it’s a good tutorial i did the same as you said in it but my program is not firing the send email event every 5 mins it just sends the email first time i run the service then after 5 mins and after that no mails sending out need some help on this
rami. . please update my querry i have raised.. it will be useful to me..
wohhh…Its very good article
why after i adding code inside the birthdayemailservice.cs, the program.cs will having an error says that birthdayemailservice is a namespace but use like a type?
there is a slight problem in flow.
bool result = email.SendEmailAsync(dr["CustomerEmail"].ToString(), dr["CustomerName"].ToString());
if (result == true)
{
eventLogEmail.WriteEntry(“Message Sent SUCCESS to – ” + dr["CustomerEmail"].ToString() +
” – ” + dr["CustomerName"].ToString());
}
even before the mail is sent or an exception arises, result returns true and its is loged.
U r really helped to me like develop this type of article.
Really awesome article.
error 1053 the service did not respond to the start or control request in a timely fashion
HI RAMI, I AM GETTING THE ABOVE ERROR, PLEASE TELL ME THE SOLUTION IF COULD.
Rami,
Thanks for ur tutorial…
But I cant find the Email Component Project.. can u please specify where it was.
and in vb.net?? how ?? please
sir …this is the best article….bt i wanna noe somethng..wot if i want to send mail before the target date….
not getting mail.
@Sushan – you need to change your SQL Logic..thats it..
@Javier – Please use Online C# to VB Converter – http://www.developerfusion.com/tools/convert/csharp-to-vb/
Ashok – Probably this can help you – http://support.microsoft.com/kb/839174
@Mangesh – Have you cross checked your SMTP Settings, check them, please troubleshoot and let me know.
@Nitin – you should be able to find it in PART – 1.
@Ashok – For the Error, I think you need to run the EXE with Administrative Privileges
@Qaaz, have you completed this tutorial as described, in that case you shouldn’t get any error.
@Jagdesh – This Service runs only once a day, Please checkout the usage of FLAG in code.
@Satinder – Good Catch. I will correct it in my next revision.
Nice Article For creating Windows Services.
Thank You
My Application is working fine but i can’t get mail
can you tell me what’s the issue?????
@chirag – there can be numerous reasons from this, try troubleshooting your SMTP, check your Server Ports, also check your email inbox in span folder.
i m working on similiar application and i wish to mail my txt file that get the log entries daily at a particular tym say 4:00 am …can u help me wid that
@Aashi – I think with slightest modifications to this prototype, you achieve it. Please let me know where you get stuck, then we can talk and resolve. But developing complete prototype for you may not be possible, because of my current schedule.
Dear friend,
I want to send email which contain data from gridview in excel then then send through button click can I send that email which have attachment through this process and if an alternate method please share.
Thanks,
Regards,
Shaz khan
@Shaz –
Yes Definitely you can send attachment through code. for that see this resource – http://www.intstrings.com/ramivemula/c/how-to-send-an-email-using-c-net-with-complete-features/
Also to send Gridview to excel – http://www.aspsnippets.com/Articles/Export-GridView-To-Word-Excel-PDF-CSV-Formats-in-ASP.Net.aspx
Thanks,