banner



How To Send An Email From Service Application C#

  • Updated date Feb 17, 2015
  • 410.7k
  • 12

This article explains how to create a Windows Service to schedule daily mail at a specified time.

Introduction

In this article I am explaining how to create a Windows Service to schedule daily mail at a specified time. Scheduling email and sending the email is a basic requirement of any project.

Step 1

Open Visual Studio and create a new project. Under Windows Desktop select Windows Service and provide a proper name and click on the OK button.

window service

Step 2

Rename the service1 class to a proper name. In this case I am using mail service. Click on "Click here to switch to code view".

mail service

Step 3

Add some app settings in the app.config file as in the following:

  1. <appSettings>
  2.    <add key="StartTime"  value= "08:33 PM " />
  3.    <add key="callDuration"  value= "2" />
  4.    <add key="CallType"  value= "1" />
  5.    <add key="FromMail"  value= "****" />
  6.    <add key="Password"  value= "****" />
  7.    <add key="Host"  value= "smtpout.secureserver.net" />
  8. </appSettings>

Step 4

In the MailService class write the following function.

  1. public  Scheduler()
  2. {
  3.    InitializeComponent();
  4.    int  strTime = Convert.ToInt32(ConfigurationManager.AppSettings[ "callDuration" ]);
  5.    getCallType = Convert.ToInt32(ConfigurationManager.AppSettings["CallType" ]);
  6.    if  (getCallType == 1)
  7.    {
  8.       timer1 =new  System.Timers.Timer();
  9.       double  inter = ( double )GetNextInterval();
  10.       timer1.Interval = inter;
  11.       timer1.Elapsed +=new  ElapsedEventHandler(ServiceTimer_Tick);
  12.    }
  13.    else
  14.    {
  15.       timer1 =new  System.Timers.Timer();
  16.       timer1.Interval = strTime * 1000;
  17.       timer1.Elapsed +=new  ElapsedEventHandler(ServiceTimer_Tick);
  18.    }
  19. }

Note: For using the ConfigurationManager add the reference first and then use the class.

  1. private double  GetNextInterval()
  2. {
  3.    timeString = ConfigurationManager.AppSettings["StartTime" ];
  4.    DateTime t = DateTime.Parse(timeString);
  5.    TimeSpan ts =new  TimeSpan();
  6.    int  x;
  7.    ts = t - System.DateTime.Now;
  8.    if  (ts.TotalMilliseconds < 0)
  9.    {
  10.       ts = t.AddDays(1) - System.DateTime.Now;
  11.    }
  12.    return  ts.TotalMilliseconds;
  13. }
  14. private void  SetTimer()
  15. {
  16.    try
  17.    {
  18.       double  inter = ( double )GetNextInterval();
  19.       timer1.Interval = inter;
  20.       timer1.Start();
  21.    }
  22.    catch  (Exception ex)
  23.    {
  24.    }
  25. }

In the timer OnStart() function first write a message to the log that the service has been started and when the service stops write to the log that the service has stopped.

  1. protected override void  OnStart( string [] args)
  2. {
  3.     timer1.AutoReset =true ;
  4.     timer1.Enabled =true ;
  5.     ServiceLog.WriteErrorLog("Daily Reporting service started" );
  6. }
  7. protected override void  OnStop()
  8. {
  9.     timer1.AutoReset =false ;
  10.     timer1.Enabled =false ;
  11.     ServiceLog.WriteErrorLog("Daily Reporting service stopped" );
  12. }

Here I am creating a class ServiceLog that contains the followings function.

  1. public static void  WriteErrorLog(Exception ex)
  2. {
  3.     StreamWriter sw =null ;
  4. try
  5.     {
  6.         sw =new  StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt" , true );
  7.         sw.WriteLine(DateTime.Now.ToString() +": "  + ex.Source.ToString().Trim() + "; "  + ex.Message.ToString().Trim());
  8.         sw.Flush();
  9.         sw.Close();
  10.     }
  11. catch
  12.     {
  13.     }
  14. }
  15. public static void  WriteErrorLog( string  Message)
  16. {
  17.     StreamWriter sw =null ;
  18. try
  19.     {
  20.         sw =new  StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt" , true );
  21.         sw.WriteLine(DateTime.Now.ToString() +": "  + Message);
  22.         sw.Flush();
  23.         sw.Close();
  24.     }
  25. catch
  26.     {
  27.     }
  28. }

This class also contains a function that will send email to the mail id passed by its arguments.

  1. #region Send Email Code Function
  2. public static void  SendEmail(String ToEmail, string  cc, string  bcc, String Subj, string  Message)
  3.      {
  4. string  HostAdd = ConfigurationManager.AppSettings[ "Host" ].ToString();
  5. string  FromEmailid = ConfigurationManager.AppSettings[ "FromMail" ].ToString();
  6. string  Pass = ConfigurationManager.AppSettings[ "Password" ].ToString();
  7.          MailMessage mailMessage =new  MailMessage();
  8.          mailMessage.From =new  MailAddress(FromEmailid);
  9.          mailMessage.Subject = Subj;
  10.          mailMessage.Body = Message;
  11.          mailMessage.IsBodyHtml =true ;
  12. string [] ToMuliId = ToEmail.Split( ',' );
  13. foreach  ( string  ToEMailId in  ToMuliId)
  14.          {
  15.              mailMessage.To.Add(new  MailAddress(ToEMailId));
  16.          }
  17. string [] CCId = cc.Split( ',' );
  18. foreach  ( string  CCEmail in  CCId)
  19.          {
  20.              mailMessage.CC.Add(new  MailAddress(CCEmail));
  21.          }
  22. string [] bccid = bcc.Split( ',' );
  23. foreach  ( string  bccEmailId in  bccid)
  24.          {
  25.              mailMessage.Bcc.Add(new  MailAddress(bccEmailId));
  26.          }
  27.          SmtpClient smtp =new  SmtpClient();
  28.          smtp.Host = HostAdd;
  29.          smtp.EnableSsl =false ;
  30.          NetworkCredential NetworkCred =new  NetworkCredential();
  31.          NetworkCred.UserName = mailMessage.From.Address;
  32.          NetworkCred.Password = Pass;
  33.          smtp.UseDefaultCredentials =true ;
  34.          smtp.Credentials = NetworkCred;
  35.          smtp.Port = 3535;
  36.          smtp.Send(mailMessage);
  37.      }
  38.      

Related Posts

0 Response to "How To Send An Email From Service Application C#"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel