如何在ASP.NET中使用Windows任务计划程序

时间:2017-05-25 19:30:46

标签: asp.net scheduled-tasks taskscheduler

我正在尝试在Window Task Scheduler中使用ASP.NET。我想在特定时间发送电子邮件。 但ASP.NET不是作为EXE运行的,它具有动态IP地址。 我不知道在ASP.NET中使用Window Task Scheduler。 你能给我任何解决方案吗?

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);
                }
            }
        }
    }


}

2 个答案:

答案 0 :(得分:0)

它应该是一个控制台应用程序,其中包含您的代码。在bin文件夹中,它将创建一个.exe文件,您需要在Windows任务计划程序中使用它。 以下链接为您提供了有关如何在Windows任务计划程序中创建任务的分步过程。

http://www.digitalcitizen.life/how-create-task-basic-task-wizard

答案 1 :(得分:0)

您应该使用Quartz.Net之类的任务计划程序。它允许您将类定义为Jobs,然后根据计划执行这些作业。我目前正在一些内部项目中使用它,它的表现与广告一样。

<强> EDITED

检查answers here