Skip to main content

Technical

Sending Emails Automatically and Periodically Using C#

A group of diverse coworkers working on the computer together

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:

  1. Windows Service
  2. Event Log
  3. SMTP Client
  4. Creating the Automatic Mail Service
  5. Creating the Windows Service Installer
  6. Creating the Windows Setup Project and installing the Service
  7. 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.

Example 1

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.

Example 2

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.

example 3

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:

example 4

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.

example 5

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.

example 6

From the Toolbox->Components->Select EventLog Component, Drag the EventLog component, and drop it in the Designer.

example 7

Coding the Project Logic

Right-click in the designer view and click View Code.

example 8

In the Constructor, add the logic (see above) to check whether the event source exists or not.

Example 9

Include the namespace “System.Threading” and add all the code below, create all the methods and properties as needed.

example 11

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.

example 13

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,

example 14

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.

example 15

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.

example 16

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.)

example 17

Set the properties as shown below.

example 18 Example 19

 

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

Example 20

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.

example 21

Then right-click the new Installer Project, Add a new “Project Output,” and click ok.

example 22example 23

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.

example 24

On this tab, you’ll see some folders that will perform some custom actions (Instal, Uninstall, etc.)

example 25

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.

example 26

 

example 27

 

After clicking ok, the primary output will be added to all the Custom Actions as follows.

example 28

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.

example 29

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.

example 30

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.

example 31

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Josué Sáenz

Being in love with music his whole life, he taught himself how to cook and play guitar. From 2009 through 2012, he played heavy metal covers from famous bands like Metallica, Iron Maiden, Megadeth, and many more in nightclubs in the city. In 2012 he started his programming career.

More from this Author

Categories
Follow Us