This article explain how to send mail automatically using C# with window service.
Introduction
This article explain how to send mail automatically using window service, Concepts are involved for sending mail automatically are SMTP Server for sending mails, Window service used to mail automatically, Event log is used to see whether the window service is working, below explain detail.1. Window Service2. Event Log3. SMTP Client4. Timer Concepts5. Steps to Create Automatic Mail Service6. Create Windows Service Deployment project7. Instal and Un-install the windows servie project8. Start and Stop your service9. View your log files
1.Window Service
Windows Service is used to create a application to run in a windows sessions. windows service can automatically run, restart or paused when the system boots , we do not show any user interface for doing the window service.In .Net framework support two type of windows service. window service can run in a single process to be create in Win32ownprocess and the service can share the process to be create in win32shareprocess. we can retrieve the information of the process using servicetype property.They are two overrides method are used to Start and Stop your windows service.1. Start methodprotected override void OnStart(string[] args) { //Your coding}2. Stop Methodprotected override void OnStart(string[] args) { //Your coding}
2.Event Log
Eventlog class used to create or accessing the windows event logs. Administration privileges need to write to an event log for every logs.EventLog,class method are used to read from existing logs, write entries to logs and create a logs or delete event sources.
Check whether event log exisits in system using SourceExists method, if not created already create eventlog using CreateEventSource method and write to the event SourceExamples:Create New EventLogif (EventLog.SourceExists("AutoMail")) { EventLog.CreateEventSource( "AutoMail","Mails"); } Write the information in existing logseventLog1.Source = "AutoMail"; eventLog1.Log = "Mails";
3.SMTP Server
The SMTP Server Class is used to Send Mail from a SMTP Server. .Net Framework 2.0 later supports the SMTP Server class from System.Net.Mailnamespace. It System.Net.Mail namespace supports three classa) MailMessageb) MailAddress.andc) AttachmentsMail Message is used to describe the messages.Mail Address is used to define theh sender and recipiants.Attachments is used to attach the file along with the mail.Examples:
MailMessage mailMsg = new MailMessage();MailAddress mailAddress = null;mailMsg.To.Add(tmuhilan@gmail.com); mailAddress =new MailAddress(Muhilan@maa.com.my ); mailMsg.From = mailAddress; mailMsg.Subject = "Automatic mailing";mailMsg.Body = "Tomorrow Meeting at 6.30PM";SmtpClient smtpClient = new SmtpClient("97.0.0.6", Convert.ToInt32(25));System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(); smtpClient.Credentials = credentials;smtpClient.Send(mailMsg);Here i have used ipaddress and Port number is our SMTP server. So change the ip and port according to your SMTP Server configuration.
4. Timer Concepts
.Net providers timer component is a server-based timer allows you to specify interval and the elapsed event is raised in your application. This event to provide regular processing. while create a service that uses a timer to periodically , it will check the server is running or not.While service could attempt to restart the server, timer component raises the elapsed event based on the value of the interval property.Examples:System.Timers.Timer time = new System.Timers.Timer(); time.Start(); time.Interval = 300000; time.Elapsed += time_elapsed;
public void time_elapsed(object sender, ElapsedEventArgs e) { }
5. Steps
- Create New Project under Visual Studio -> File -> New -> Project -> Select Project Types -> Visual C# and choose windows service
- Change Service name as per your naming standard
- From Toolbox -> Components ->Select Eventlog component. Drag the Eventlog component and drop in design.
- Rightclick and choose view code , In constructor check whether the event log exists or not , if not exists create the event log.
- Examples:
if (!System.Diagnostics.EventLog.SourceExists("MailSend")) {System.Diagnostics.EventLog.CreateEventSource( "MailSend", "AutoMailLog"); }MyLogEvent.Source = "MailSend"; MyLogEvent.Log = "AutoMailLog";
6. Next onStart Override method
Here , create timer component and assign the interval values and other properties
MyLogEvent.WriteEntry("In OnStart --- Sending Mail to" + Dt); System.Timers.Timer time = new System.Timers.Timer(); time.Start(); time.Interval = 300000; time.Elapsed += time_elapsed;
time_elapsed event to be call for every 5 minutes
public void time_elapsed(object sender, ElapsedEventArgs e) {MyLogEvent.WriteEntry("Mail Sending on " + DateTime.Now.ToString()); SendEmail("Muhilan@maa.com.my", "tmuhilan@gmail.com", "Automatic Mail sending", "Successfully working contact tmuhilan@gmail.com"); }7. Here SendEmail is my function for sending mail
public bool SendEmail(string strTo, string strFrom, string strSubject, string strBody) {bool flag = false; MailMessage mailMsg = new MailMessage(); MailAddress mailAddress = null; try {// To mailMsg.To.Add(strTo);mailAddress = new MailAddress(strFrom); mailMsg.From = mailAddress;mailMsg.Subject = strSubject; mailMsg.Body = strBody;SmtpClient smtpClient = new SmtpClient("97.0.0.6", Convert.ToInt32(25)); System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(); smtpClient.Credentials = credentials; smtpClient.Send(mailMsg);flag = true; MyLogEvent.WriteEntry("Mail Send Successfully"); }catch (Exception ex) { MyLogEvent.WriteEntry("Error occured"); //Response.Write(ex.Message); }finally {mailMsg = null; mailAddress = null; }return flag; }8. Once written coding , compile if no error occurs. Then
9. Rightclick in design mode ->Select Add installer -> it will create two components
a) ServiceProcessInstaller and b) ServiceInstaller
a) ServiceProcessInstaller is used to define the windows service work in which account.Here we can set the account type as LocalSystem , User,Network service. In my project i have used LocalSystem.
b)ServiceInstaller Set ServiceName as anything(AutoMail) and Starttype as Automatic
10. Once Set the property and Build. Now created web service.
6. Create windows service depolyment project
- In solution explorer, Add new project -> select setup and deployment under other project types
- Right click the project -> Add -> Project Output
- In a project item for the primary output of your service is added to the setup project.
- Now to add a custom action to install the service.exe file.
5. In Solution Explorer, right-click the setup project -> point to View -> then choose Custom Actions.
The Custom Actions editor appears.
- In the Custom Actions editor, right-click the Custom Actions node and choose Add Custom Action.The Select Item in Project dialog box appears.
- Double-click the Application Folder in the list box to open it, select Primary Output from Service (Active), and click OK.The primary output is added to all four nodes of the custom actions
- Install, Commit, Rollback, and Uninstall.
- In Solution Explorer, right-click the ServiceSetup project and choose Build.
7. To install the Windows Service
To install service.exe, right-click the setup project in the Solution Explorer and select Install.If you want to unistall your service , right-click the sertup project in the solution explorer and select uninstall options.
8. Stop and Start your service
1. For Xp windows-> click Start, point to Programs-> My Computer -> rightclick-> then select Manage2. Computer Management Consle windows will appear3. Select the Service and Applications node , in the sub node select services , there
4. Select your service in the list, right-click it, and then click Start.
5. Right-click the service, and then click Stop.