Search code examples
asp.netscheduled-taskswindows-task-scheduler

How to use Windows task Scheduler in ASP.NET


I am trying to use ASP.NET in Window Task Scheduler. I want to send the email on specific time. But ASP.NET is not run as an EXE, it has a dynamic ip address. I have no idea to use Window Task Scheduler in ASP.NET. Can you give me any solutions for it?

void SendEmail()
{
    //get the data from database
    DataTable data = GetData();
    DataTable email_data = GetEmailData();

    //set DataTable Name of Excel Sheet
    data.TableName = "NSOList";

    //Create a New Workook
    using (XLWorkbook wb = new XLWorkbook())
    {
        //Add the DataTable as Excel Workhseet
        wb.Worksheets.Add(data);

        using (MemoryStream memoryStream = new MemoryStream())
        {
            //Save the Excel Workbook to MemoryStream
            wb.SaveAs(memoryStream);

            //Convert MemoryStream to Byte array
            byte[] bytes = memoryStream.ToArray();
            memoryStream.Close();

            //body with embedded image
            AlternateView body = AlternateView.CreateAlternateViewFromString
                ("Hi <br><br> <img src=cid:example>", null, "text/html");

            //create the LinkedResource (embedded image)
            LinkedResource image = new LinkedResource("c:\\example.png");
            image.ContentId = "example";

            //add the LinkedResource to the appropriate view
            body.LinkedResources.Add(image);


            String from = "abcd@abcd.net";
            //bring Email data
            for (int i = 0; i < email_data.Rows.Count; i++)
            {
                String to = email_data.Rows[i][0].ToString();


                using (MailMessage mm = new MailMessage(from, to))
                {

                    SmtpClient smtp = new SmtpClient();
                    mm.Subject = "List";

                    mm.AlternateViews.Add(body);
                    mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "NSOList.xlsx"));
                    mm.IsBodyHtml = true;

                    smtp.Host = "smtp.gmail.com";
                    smtp.EnableSsl = true;
                    System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
                    credentials.UserName = "abcd@gmail.com";
                    credentials.Password = "abcd";
                    smtp.UseDefaultCredentials = true;
                    smtp.Credentials = credentials;
                    smtp.Port = 587;
                    smtp.Send(mm);
                }
            }
        }
    }


}

Solution

  • You should use a Task Scheduler like Quartz.Net. It allows you to define classes as Jobs, and then execute those jobs according to an schedule. I'm currently using it in some in-house projects and it performs as advertised.