This article quickly explains how to send an email automatically and periodically using Windows Service, SMTP Server (for sending the emails), Event Logs, and many more technologies or concepts.
Table of Contents:
- Windows Service
- Event Log
- SMTP Client
- Creating the Automatic Mail Service
- Creating the Windows Service Installer
- Creating the Windows Setup Project and installing the Service
- Starting, Stopping the service manually, and reviewing the event log source
Windows Services
NT Services, better known as Windows Services, are a core component of the Microsoft Windows Operating System. Windows Services enable you to create long-running executable applications that run on a window session. These services can be automatically started, paused, and restarted and do not show any user interface. You can easily create services by creating an application that is installed as a service.
On every Windows Service you create, there are 2 overridden methods that are very important and commonly used to Start and Stop the service.
In the code above, we have the functions OnStart and OnStop, where the window service can stop or start the main tasks to be performed.
Event Log
EventLog Class uses the windows event log. with this control, we write events to the system log. This can help with debugging on your user’s systems, partly because no special software needs to be installed to use the event log. Whenever you want to access those logs, you can use the Event Viewer.
You can find your event source in the Applications and Services Logs folder.
Also, remember to always validate whether the event source exists in the system using the SourceExists method. If not created, you can create a new event source using the CreateEventSource method.
You instantiate the EventLog variable and as a good practice, you validate first if the event source exists, and if not, create the event source with the CreateEventSource method. Then, just set the event source and Log name to the EventLog that will be used (in this example, IPSLog).
SMTP Client
SMTP stands for “Simple Mail Transfer Protocol,” a protocol for sending e-mail messages between servers. Most e-mail systems that send mail over the Internet use SMTP to send messages from one server to another. the default TCP port used by SMTP is 25.
The .NET library (which I used for this part of the program) provides the namespaces:
- {} System.Net
- {} System.Net.Mail
and we are going to use the following classes from the namespaces listed above:
- MailMessage
- MailAddress
- NetworkCredential
- SmtpClient
Before starting, let’s briefly review the three classes above:
MailMessage
Represents an email message that can be sent using the SmtpClient class. Instances from this class can be used to construct e-mail messages that are transmitted to an SMTP server.
MailAddress
Represents an address with information for e-mail messages and is used by SmtpClient and MailMessage. It is composed of a User name, Host name, and, optionally, a DisplayName.
NetworkCredential:
It is a base class that supplies credentials in password-based authentication schemes. Classes that implement the ICredentials interface return a NetworkCredential object (this class does not support public key-base Auth such as SSL).
SmptClient:
Allows applications to send an e-mail by using the Simple Mail Transfer Protocol (SMTP). This class is used to send e-mails to an SMTP server for delivery.
Sample C# Code:
The first lines of code hold the Client information (Host, Port, Credentials, etc.) for sending the mail through the server, the sender address, the address to whom the mail is going to be sent, and the message content.
In the last piece of code, we send the mail using the Send method, and if any exception is raised, it’s caught, and the code tries to send the mail again.
Creating the Automatic Mail Service
Now, after a brief explanation of some of the concepts and technologies used in this example, we’ll continue with the steps to create the Windows Service in Visual Studio. The Project Installer extension can be either downloaded from Visual Studio in the Extensions and Updates dialog by selecting the online node and searching for “Visual Studio Installer Project Extension,” or you can download it directly from this page https://marketplace.visualstudio.com/items?itemName=VisualStudioProductTeam.MicrosoftVisualStudio2017InstallerProjects.
Create and Setup the Project
Create the main project in Visual Studio 2017 under File->New->Project.
Select Visual C#->Windows Classic Desktop or search for Windows Service, select the Windows Service option, and set a name according to your company naming standard. click OK.
From the Toolbox->Components->Select EventLog Component, Drag the EventLog component, and drop it in the Designer.
Coding the Project Logic
Right-click in the designer view and click View Code.
In the Constructor, add the logic (see above) to check whether the event source exists or not.
Include the namespace “System.Threading” and add all the code below, create all the methods and properties as needed.
Add this code to the OnStop Method to log when the Windows Service has stopped
This Method needs the last date a mail was sent and the fixed days, hours, or minutes to calculate and return the new date to send emails.
SendMail method iterates through a mail list, creates the mail body for each one of them, and sends the created mail using the OnSendEmail method,
OnSendEmail creates a Task that will asynchronously send the mail, create the Client using a given host, port, and credentials, and set up the sender and the mail to whom it will be sent.
Creating the Windows Service Installer
Once you have written all the code needed and changed everything you needed to change in the code, compile it to see if there’s no error (otherwise, try to fix the errors before continuing). After a successful build, right-click in the design mode and select the option Add Installer. This will generate two components.
Those components are:
- ServiceProcessInstaller: Used to define in which Account the Windows Service will work. Here we can set the account type as LocalSystem, User, Network Service, etc.
- ServiceInstaller: Here, we can define the ServiceName property as desired (IPSMailing) and choose the StartType (automatic, manual, etc.)
Set the properties as shown below.
Creating the Windows Service Setup Project
After creating the Installer for the service, you will create the Setup project for the windows service. It is very useful as it contains the project that will be deployed. Follow the next steps to install and set the Setup Project in the solution (in previous versions, it could be named Deployment Project).
Go to Solution Explorer->Solution->Add->New Project
Select Setup Project from Other Project Types->Visual Studio Installer (Install the Visual Studio Project Installer Extension for visual studio 2017 mentioned at the beginning of the “Creating the Automatic Mail Service” chapter if you can’t find the Setup Project). You can use any name.
Then right-click the new Installer Project, Add a new “Project Output,” and click ok.
Now to install the custom actions to let the solution install the Service.exe file, first right-click the SetupMailInstaller project and Select View->Custom Actions.
On this tab, you’ll see some folders that will perform some custom actions (Instal, Uninstall, etc.)
Now right-click the Custom Action node and choose the option Add Custom Action. Then, double-click the Application Folder and select the “Primary output from IPSMailScheduler (Active),” and click Ok.
After clicking ok, the primary output will be added to all the Custom Actions as follows.
Now just right-click on the SetupMailService project and choose the Build option. If the build succeeds, right-click the project again and select the Install option. If you want to Uninstall the service, right-click the project and select Uninstall.
Starting, Stopping the Service Manually and Reviewing the Event Log Source
To Stop, Start, Restart or change some of the properties of the service, you have to start the Windows Services console. Click the Start Menu->Settings->Control Panel, then double click the Administrative Tools->Services, and the Services console appears. Another method is to open the Start Menu and search for Run, and start the “services.msc ” to run the Services console.
And to access the event log source, just click Start, point to Control Panel, point to Administrative Tools, and then double-click Event Viewer. In Applications and Services Logs you’ll find the IPSScheduler source and all the logs created when the code ran.