Search
Sponsor
Winners

Win Prizes

Social Presence
Twitter Twitter LinkedIn YouTube Google

Like us on Facebook
Advertisements
Top Articles Author
Fri, 21-Nov-2014 Authors
All Time Authors
Sourav.Kayal
39750
Sheonarayan
38050
Niladri.Biswas
33350

Latest members | More ...


(Statistics delayed by 5 minutes)
Ads
 Article

How to send mail automatically for every five minutes using C#?

Muhilan
Posted by under ASP.NET category on for Beginner level | Views : 393095 red flag
If you found plagiarised (copied) or inappropriate content,
please let us know the original source along with your correct email id (to communicate) for further action.
Rating: 4.29 out of 5
7 vote(s)
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 Service
2. Event Log
3. SMTP Client
4. Timer Concepts
5. Steps to Create Automatic Mail Service
6. Create Windows Service Deployment project
7. Instal and Un-install the windows servie project
8. Start and Stop your service
9. 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  method
 
protected override void OnStart(string[] args)
{
   //Your coding
}
2. Stop Method
protected 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 Source
 
Examples:
Create New EventLog
 
if (EventLog.SourceExists("AutoMail"))
    {         
            EventLog.CreateEventSource(
                "AutoMail","Mails");
    }
 
 
Write the information in existing logs

    eventLog1.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.Mail namespace. 
 
It System.Net.Mail namespace supports three class
 
a) MailMessage
b) MailAddress.and
c) Attachments
 
Mail 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

  1. Create New Project under Visual Studio -> File -> New -> Project -> Select Project Types -> Visual C# and choose windows service
  2. Change Service name as per your naming standard
  3. From Toolbox -> Components ->Select Eventlog component. Drag the Eventlog component and drop in design.
  4. Rightclick and choose view code , In constructor check whether the event log exists or not , if not exists create the event log.
  5. 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

  1.  In solution explorer, Add new project -> select setup and deployment under other project types
  2. Right click the project -> Add -> Project Output
  3. In a project item for the primary output of your service is added to the setup project.
  4. 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.

  1. In the Custom Actions editor, right-click the Custom Actions node and choose Add Custom Action.

    The Select Item in Project dialog box appears.

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

  3.  Install, Commit, Rollback, and Uninstall.

  4. 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 Manage

2. Computer Management Consle windows will appear

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

9. View your event log files

1. For Xp windows-> click Start, point to Programs-> My Computer -> rightclick-> then select Manage

2. Computer Management Consle windows will appear

3. select the System Tools node , in the sub node select Event Viewer

4. Select your event log from the list, in the right side panel you can see the event logs trigger based on your coding

 Result 

      


Conclusion


Please feel free to send your feedback. Thank you.


Page copy protected against web site content infringement by Copyscape
About the Author

Muhilan

Full Name: Muhil an
Member Level:
Member Status: Member
Member Since: 11/30/2009 2:46:25 AM
Country: India

working as an IT System Analyst,tmuhilan at gmail com
Login to vote for this post.
Found interesting? Add this to:


Comments or Responses

Posted by: Abhi2434 on: 6/26/2010

Good work mate.

Posted by: Mohankind on: 10/10/2012 | Points: 25

Can i get the full source code for this article. Or mail me to kmohan_1987@yahoo.com

Posted by: Ashutoshdubey72 on: 10/10/2012 | Points: 25

Hi,

Could you send full source code on my registered email id ashutoshdubey72@gmail.com because I am new developer in .net ?

Posted by: Spiderman on: 11/3/2012 | Points: 25

Hi,
Could you send me full source code on my registered mail fabio.col63@gmail.com. I'm interesting im dot.net development.
Thanks

Posted by: Tikna98 on: 12/21/2012 | Points: 25

Sir I need to create a windows service ,which will be connected with a web service ,and web service will tell ,after how many time and what data we have to send in mail ,I am able to it with single request at a time ,but not for multiple request at single time. Please help me out

Posted by: Muhilan on: 12/21/2012 | Points: 25

Tikna , i cant understand your requirement.. please mail to tmuhilan@aol.com

Posted by: Chpraveen31 on: 12/29/2012 | Points: 25

Nice article saved my days..thanks alot

Posted by: Kopirock on: 1/2/2013 | Points: 25

hi can you send me the full source @ kopirock@gmail.com
Thank you very much :)

Posted by: Ankit_Parmar555 on: 1/18/2013 | Points: 25

all mention steps are done
at time of installing it is asking for user name and password.
in that what should i need to enter.
i tried with my email id password but still giving error.
(no mapping between account names and security was done)

Posted by: Drizzt on: 2/14/2013 | Points: 25

Hi thanks for your article

Could you please share the full code to my baristam35@hotmail.com email adress? Because i was trying to do a program like this to my company.

Grazie

Posted by: Syedzubair57 on: 2/18/2013 | Points: 25

Can i get the full source code for this article. Or mail me to syed-business571@hotmail.com thanku..

Posted by: Qwerty99 on: 4/23/2013 | Points: 25

Good article. Could you send full source code to mail damian385@gmail.com
Thanks


Posted by: Tt on: 8/2/2013 | Points: 25

Good article. Could you send full source code to mail atengteng@hotmail. com Thanks

Posted by: Emma.Sun.Sts on: 11/14/2013 | Points: 25

Hi! This article helps a lot! Thanks.

I can send scheduled email. But when I tried to extract data from web, write that data in .txt file and email that data as scheduled, the program hangs at new StreamWriter declaration. I really don't know what is happening. I'm quite new to C#. Can you help? This is my code.

public void importFrmURL(string url, string dir) // dir = @"\Import1.txt"
{
System.IO.StreamWriter fileWriter;
fileWriter = new System.IO.StreamWriter(dir); //<---PROBLEM------ hang there
try
{
var client = new WebClient();
using (var stream = client.OpenRead(url))
using (var reader = new StreamReader(stream))
{
string line;
while ((line = reader.ReadLine()) != null)
{
fileWriter.WriteLine(line);
}
fileWriter.Close();
}//---------------------------------------------------------------------------------
}
catch (Exception e)
{
eventLog1.WriteEntry("Error occurred!\n\r" + e.ToString());//<---DEBUG
}
}

Posted by: Muhilan on: 11/14/2013 | Points: 25

System.IO.StreamWriter fileWriter;
fileWriter = new System.IO.StreamWriter(dir);

dir should be file path for ex... c:\import1.txt like that

Posted by: Rumeel2004 on: 1/1/2014 | Points: 25

Hi,
Good article. Could you send full source code to mail Rumeel2004@yahoo.com Thanks

Posted by: Janath on: 10/31/2014 | Points: 25

Hi sir,Could you pleas send the full source code to janath22@gmail.com
Thanks:)

Login to post response

Comment using Facebook(Author doesn't get notification)