Click here to Skip to main content
15,307,068 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am doing a windows service to send automatic emails to the (stored in database) mail ids when certain condition occurs(say on every Wednesday),the code of the service1.cs is given below

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Data.OleDb;
using System.Net.Mail;
namespace AutomaticEmailSystem
    public partial class AutomaticEmailSystem : ServiceBase
        private System.Data.OleDb.OleDbConnection conn;
        public AutomaticEmailSystem()
      static void Main()
            System.ServiceProcess.ServiceBase[] ServicesToRun;
            // More than one user Service may run within the same process. To add
            // another service to this process, change the following line to
            // create a second service object. For example,
            //   ServicesToRun = new System.ServiceProcess.ServiceBase[] {new Service1(), new MySecondUserService()};
            ServicesToRun = new System.ServiceProcess.ServiceBase[] { new AutomaticEmailSystem() };
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
       private void start()
            this.conn = new System.Data.OleDb.OleDbConnection();
            // conn
            this.conn.ConnectionString = @"Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;Data Source=""C:\Email.mdb"";Mode=Share Deny None;Jet OLEDB:Engine Type=5;Provider=""Microsoft.Jet.OLEDB.4.0"";Jet OLEDB:System database=;Jet OLEDB:SFP=False;persist security info=False;Extended Properties=;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Create System Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;User ID=Admin;Jet OLEDB:Global Bulk Transactions=1";
            // GoodDay
            this.CanHandlePowerEvent = true;
            this.CanPauseAndContinue = true;
            this.CanShutdown = true;
            this.ServiceName = "AutomaticEmailSystem";
    /*    protected override void Dispose(bool disposing)
            if (disposing)
                if (components != null)
        DataSet ds = new DataSet();
        protected override void OnStart(string[] args)
                 // TODO: Add code here to start your service.
                 OleDbDataAdapter da = new OleDbDataAdapter("select * from Email", conn);
                 string day = Convert.ToString(DateTime.Now.DayOfWeek);
                 if (day == "Wednesday")
                     foreach (DataRow dr in ds.Tables[0].Rows)
                         MailMessage mail = new MailMessage();
                         SmtpClient SmtpServer = new SmtpClient("");
                         mail.From = new MailAddress("");
                         string to = dr["mailid"].ToString();
                         mail.Subject = "Stock And Sale Reports";
                         string mailtxt = "";
                         mail.IsBodyHtml = true;
                         mailtxt = "Hi " + to + ",";
                         mailtxt = mailtxt + "Good Day." + "</b></font><br><br>";
                         mailtxt = mailtxt + "<font face='verdana' color='#008080'><b>" + "May today be filled with sunshine and smile, laughter and love." + "</b></font><br><br>";
                         mailtxt = mailtxt + "<font face='verdana' color='#008080'><b>" + "Find the attached Stock and Sale Reports." + "</b></font><br><br>";
                         mailtxt = mailtxt + "<font face='verdana' color='#0000FF'><b>Cheers!" + "<br><br>";
                         mailtxt = mailtxt + "<font face='verdana' color='#0000FF'><b>Regards!" + "<br><br>";
                         mailtxt = mailtxt + "<font face='verdana' color='#0000FF'><b>" + "<br><br>";
                         //  mm.Body = mailtxt;
                         mail.Body = mailtxt;
                         System.Net.Mail.Attachment attachment,att;
                         attachment = new System.Net.Mail.Attachment("c:\\Stock_Report.xls");
                         att = new System.Net.Mail.Attachment("c:\\Sale_Report.xls");
                         SmtpServer.Port = 587;
                         SmtpServer.Credentials = new System.Net.NetworkCredential("*****", "******");
                         SmtpServer.EnableSsl = true;
                       eventLog1.WriteEntry("Automatic Email Service Started");
                     AutomaticEmailSystem aa = new AutomaticEmailSystem();
                     ///////Stop service manually  jst
             catch (System.Exception ex)
                 string excep = ex.ToString();

        protected override void OnStop()
            // TODO: Add code here to perform any tear-down necessary to stop your service.

But this service is not sending any mails to the stored mail ids.I dont find where the problem is.Kindkly give your helpful comments.
All your advices are appreciable !

john sathish
Updated 8-Dec-10 5:32am

0) Do you need credentials to send mail through the specified server?

1) Have you tried using the event log to discover what your service is dowing and in what order?

2) Have you ever tried the debugger?

3) Have you tried putting the code into a console app to see if it even works? (Easier to dbug this way as well)
John Sathish Tamilarasu 8-Dec-10 11:44am
yes john i use the same code in a console app,it works and i got an email.i am using credential as SmtpServer.Credentials = new System.Net.NetworkCredential("*****", "******");
but still its not working
This isn't what services are for, this is what scheduled tasks are for. The way this is implemented right now the only time that it will send anything is if the service is started on a Wednesday, and then it'll only do it's thing ONCE when it's started. This really looks like it should be a console app that's scheduled to run every Wednesday instead of being a service.

If you want to keep it a service you'll need to make a timer or thread or something to wake up periodically and run your email code, but only on Wednesdays.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900