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.
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".
Step 3
Add some app settings in the app.config file as in the following:
- <appSettings>
- <add key="StartTime" value= "08:33 PM " />
- <add key="callDuration" value= "2" />
- <add key="CallType" value= "1" />
- <add key="FromMail" value= "****" />
- <add key="Password" value= "****" />
- <add key="Host" value= "smtpout.secureserver.net" />
- </appSettings>
Step 4
In the MailService class write the following function.
- public Scheduler()
- {
- InitializeComponent();
- int strTime = Convert.ToInt32(ConfigurationManager.AppSettings[ "callDuration" ]);
- getCallType = Convert.ToInt32(ConfigurationManager.AppSettings["CallType" ]);
- if (getCallType == 1)
- {
- timer1 =new System.Timers.Timer();
- double inter = ( double )GetNextInterval();
- timer1.Interval = inter;
- timer1.Elapsed +=new ElapsedEventHandler(ServiceTimer_Tick);
- }
- else
- {
- timer1 =new System.Timers.Timer();
- timer1.Interval = strTime * 1000;
- timer1.Elapsed +=new ElapsedEventHandler(ServiceTimer_Tick);
- }
- }
Note: For using the ConfigurationManager add the reference first and then use the class.
- private double GetNextInterval()
- {
- timeString = ConfigurationManager.AppSettings["StartTime" ];
- DateTime t = DateTime.Parse(timeString);
- TimeSpan ts =new TimeSpan();
- int x;
- ts = t - System.DateTime.Now;
- if (ts.TotalMilliseconds < 0)
- {
- ts = t.AddDays(1) - System.DateTime.Now;
- }
- return ts.TotalMilliseconds;
- }
- private void SetTimer()
- {
- try
- {
- double inter = ( double )GetNextInterval();
- timer1.Interval = inter;
- timer1.Start();
- }
- catch (Exception ex)
- {
- }
- }
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.
- protected override void OnStart( string [] args)
- {
- timer1.AutoReset =true ;
- timer1.Enabled =true ;
- ServiceLog.WriteErrorLog("Daily Reporting service started" );
- }
- protected override void OnStop()
- {
- timer1.AutoReset =false ;
- timer1.Enabled =false ;
- ServiceLog.WriteErrorLog("Daily Reporting service stopped" );
- }
Here I am creating a class ServiceLog that contains the followings function.
- public static void WriteErrorLog(Exception ex)
- {
- StreamWriter sw =null ;
- try
- {
- sw =new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt" , true );
- sw.WriteLine(DateTime.Now.ToString() +": " + ex.Source.ToString().Trim() + "; " + ex.Message.ToString().Trim());
- sw.Flush();
- sw.Close();
- }
- catch
- {
- }
- }
- public static void WriteErrorLog( string Message)
- {
- StreamWriter sw =null ;
- try
- {
- sw =new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt" , true );
- sw.WriteLine(DateTime.Now.ToString() +": " + Message);
- sw.Flush();
- sw.Close();
- }
- catch
- {
- }
- }
This class also contains a function that will send email to the mail id passed by its arguments.
- #region Send Email Code Function
- public static void SendEmail(String ToEmail, string cc, string bcc, String Subj, string Message)
- {
- string HostAdd = ConfigurationManager.AppSettings[ "Host" ].ToString();
- string FromEmailid = ConfigurationManager.AppSettings[ "FromMail" ].ToString();
- string Pass = ConfigurationManager.AppSettings[ "Password" ].ToString();
- MailMessage mailMessage =new MailMessage();
- mailMessage.From =new MailAddress(FromEmailid);
- mailMessage.Subject = Subj;
- mailMessage.Body = Message;
- mailMessage.IsBodyHtml =true ;
- string [] ToMuliId = ToEmail.Split( ',' );
- foreach ( string ToEMailId in ToMuliId)
- {
- mailMessage.To.Add(new MailAddress(ToEMailId));
- }
- string [] CCId = cc.Split( ',' );
- foreach ( string CCEmail in CCId)
- {
- mailMessage.CC.Add(new MailAddress(CCEmail));
- }
- string [] bccid = bcc.Split( ',' );
- foreach ( string bccEmailId in bccid)
- {
- mailMessage.Bcc.Add(new MailAddress(bccEmailId));
- }
- SmtpClient smtp =new SmtpClient();
- smtp.Host = HostAdd;
- smtp.EnableSsl =false ;
- NetworkCredential NetworkCred =new NetworkCredential();
- NetworkCred.UserName = mailMessage.From.Address;
- NetworkCred.Password = Pass;
- smtp.UseDefaultCredentials =true ;
- smtp.Credentials = NetworkCred;
- smtp.Port = 3535;
- smtp.Send(mailMessage);
- }
0 Response to "How To Send An Email From Service Application C#"
Post a Comment