Click here to Skip to main content
15,901,368 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
In order to send mail daily at 5:00PM I have used Windows services. I have tested the sending mail application in windows application and then I have used in Windows services. Im thinking that there is something wrong on using the code in the service because from the service im unable to send mails.

I have one more question. Suppose if I made some modifications in the service should I uninstall and reinstall the service or restarting the service is enough?

Here is the code below that i have used in windows service.


XML
public partial class DailyAttendanceService : ServiceBase
    {
        List<int> parentId = new List<int>();
        List<string> strEmailIds = new List<string>();
        Timer timer = new Timer();
        DataTable dt;
        DataSet ds;
        public DailyAttendanceService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            timer.Interval = 1000;
            timer.Enabled = true;
           timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
        }

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            DateTime dt1 = Convert.ToDateTime(DateTime.Now.ToString("HH:mm"));
            DateTime dt2 = Convert.ToDateTime("05:00 PM");
            int result = DateTime.Compare(dt1, dt2);
            if (result == 0)
            {
                SendEmail();

            }
        }

        protected override void OnStop()
        {
            timer.Enabled = false;
        }

        public void SendEmail()
        {
            DateTime SubjectDate = Convert.ToDateTime("05/01/2013");
            string spName = "spAttendanceDet";
            SqlParameter pSubjectDate = new SqlParameter("@SubjectDate", SqlDbType.DateTime);
            SqlParameter pTotal = new SqlParameter("@total", SqlDbType.Int);
            SqlParameter pSemister = new SqlParameter("@Semister", SqlDbType.VarChar, 50);
            pSubjectDate.Value = "01 May 2013";
            pTotal.Value = 7;
            pSemister.Value = "2-1";


            ds = SqlHelper.ExecuteDataset(Helper.ConnectionString, CommandType.StoredProcedure, spName, pSubjectDate, pTotal, pSemister);
            dt = new DataTable();
            // da.Fill(ds);
            dt = ds.Tables[0];
            //DataRow dr1 = new DataRow();
            //dr1 = dt.Select("FKParentId" +)
            foreach (DataRow dr in dt.Rows)
            {
                int present = Convert.ToInt32(dr[0]);
                int total = Convert.ToInt32(dr[1]);
                int abscent = Convert.ToInt32(dr[2]);
                int fkParentId = Convert.ToInt32(dr[5]);
                string pEmailId = new ParentBO().GetParentById(fkParentId).PEmailId;


                string from = "abc@gmail.com"; //Replace this with your own correct Gmail Address

                string to = pEmailId; //Replace this with the Email Address to whom you want to send the mail




                StringBuilder strBuilder = new StringBuilder();
                strBuilder.Append("<Table>");
                strBuilder.Append("<tr>");
                strBuilder.Append("<td>");
                strBuilder.Append("Daily Attendance Report");
                strBuilder.Append("</td>");
                strBuilder.Append("</tr>");
                strBuilder.Append("<tr>");
                strBuilder.Append("<td  colspan=3>");
                strBuilder.Append("--------------------------------------------------------");
                strBuilder.Append("</td>");
                strBuilder.Append("</tr>");
                strBuilder.Append("<tr>");
                strBuilder.Append("<td>");
                strBuilder.Append("Present");
                strBuilder.Append("</td>");
                strBuilder.Append("<td>");
                strBuilder.Append("Total");
                strBuilder.Append("</td>");
                strBuilder.Append("<td>");
                strBuilder.Append("Abscent");
                strBuilder.Append("</td>");
                strBuilder.Append("</tr>");

                strBuilder.Append("<tr>");
                strBuilder.Append("<td>");
                strBuilder.Append(present);
                strBuilder.Append("</td>");
                strBuilder.Append("<td>");
                strBuilder.Append(total);
                strBuilder.Append("</td>");
                strBuilder.Append("<td>");
                strBuilder.Append(abscent);
                strBuilder.Append("</td>");
                strBuilder.Append("</tr>");

                strBuilder.Append("</Table>");

                System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
                mail.To.Add(to);


                mail.From = new MailAddress(from, "College", System.Text.Encoding.UTF8);
                mail.Subject = "Daily Attendance Report";
                mail.SubjectEncoding = System.Text.Encoding.UTF8;
                mail.Body = strBuilder.ToString();

                mail.BodyEncoding = System.Text.Encoding.UTF8;
                mail.IsBodyHtml = true;
                mail.Priority = MailPriority.High;

                SmtpClient client = new SmtpClient();
                //Add the Creddentials- use your own email id and password

                client.Credentials = new System.Net.NetworkCredential(from, "xyz");

                client.Port = 587; // Gmail works on this port
                client.Host = "smtp.gmail.com";
                client.EnableSsl = true; //Gmail works on Server Secured Layer
                try
                {
                    client.Send(mail);
                }
                catch (Exception ex)
                {
                    Exception ex2 = ex;
                    string errorMessage = string.Empty;
                    while (ex2 != null)
                    {
                        errorMessage += ex2.ToString();
                        ex2 = ex2.InnerException;
                    }

                } // end try
            }


        }
    }
Posted
Updated 24-May-13 2:23am
v2
Comments
[no name] 24-May-13 8:32am    
"im unable to send mails"... why? I do not see anywhere that you are logging any error messages. You are catching the exceptions but not doing anything with them. Did you check the event logs for errors?

1 solution

1.You don't need to reinstall service after modification. Stop the service, copy your new service exe and start service again.

2.I believe your primary thread is finished before your timer Elapsed time reached. Some how you need to keep primary thread running. You need to find your way for that.

Follow this link

http://stackoverflow.com/questions/3344633/how-to-make-a-win-service-run-long-term-with-threading[^]
 
Share this answer
 
v5
Comments
SusanDaniel 29-May-13 1:50am    
Hi Mahesh,
Thanks for the reply. The code which I have posted is working fine but the problem is, the mails are being sent daily at 3:30 PM that too nearly 6 mails at a time. I didnt fix that time anywhere and I have checked.
Mahesh Bailwal 30-May-13 1:53am    
I think best way to analyze this problem is to add logging in your service where you think it might be any issue.

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