每天晚上8点使用Windows服务发送邮件

时间:2014-10-31 09:23:39

标签: asp.net vs2010-express

以下代码每3分钟发送一次邮件。但我想每天晚上8点发送一次邮件。如何在下面的代码中设置它。

我是Windows服务的新手,所以请帮助我。我正在使用visual studio 2010

    public partial class Scheduler : ServiceBase
 {
    System.Timers.Timer createOrderTimer;
    private Timer timer1 = null;
    public Scheduler()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        System.Timers.ElapsedEventHandler(this.timer1_Tick);

        createOrderTimer = new System.Timers.Timer();
        createOrderTimer.Elapsed += new System.Timers.ElapsedEventHandler(GetMail);
        createOrderTimer.Interval = 180000;
        createOrderTimer.Enabled = true;
        createOrderTimer.AutoReset = true;
        createOrderTimer.Start();   
    }

    private void timer1_Tick(object sender, ElapsedEventArgs e)
    {
        Library.WriteErrorLog("Timer Ticked and some job has been done successfully");
    }

    protected override void OnStop()
    {
        timer1.Enabled = false;
        Library.WriteErrorLog("Test Window Service stopped");
    }

    public void GetMail(object sender, System.Timers.ElapsedEventArgs args)
    {
        NetworkCredential cred = new NetworkCredential("abc@gmail.com", "abc");
        MailMessage msg = new MailMessage();
        msg.To.Add("to@abc.com");
        msg.Subject = "Welcome Venkat";

        msg.Body = "You Have Successfully Entered to venkat World!!!";
        msg.From = new MailAddress("from@gmail.com"); // Your Email Id
        SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
        client.Credentials = cred;
        client.EnableSsl = true;
        client.Send(msg);
    }
}

2 个答案:

答案 0 :(得分:0)

查看以下库:http://www.quartz-scheduler.net/

通过这种方式,您可以非常轻松地安排任务。

您可以在stackoverflow上找到示例,即

答案 1 :(得分:0)

您每三分钟发送一次邮件。如果时间是每分钟8:00,为什么不控制,如果是,则发送邮件。您可以使用DateTime.Now获取当前时间。为了加强您的控制,您可以保留已发送邮件的日志,如果还没有,请尝试重新发送,因为发送可能会失败。

如下所示,但要知道这是一个非常简单的示例,可能会导致错误:

public void GetMail(object sender, System.Timers.ElapsedEventArgs args)
{
    if (mailSentForToday)
        return;

    if (DateTime.Now.Hour < 20)
        return;

    NetworkCredential cred = new NetworkCredential("abc@gmail.com", "abc");
    MailMessage msg = new MailMessage();
    msg.To.Add("to@abc.com");
    msg.Subject = "Welcome Venkat";

    // send the mail    
}