0

在这里,我目前在我的 SQL Server 2008 DB 中有一些日期值。当日期值等于当前日期时,我想向特定邮件地址发送电子邮件警报。想象一下一个自动化的生日祝福软件。

这是我用于电子邮件功能的代码。它可以正常工作。

private void sendMailMessage()
        {
            try
            {

                MailMessage myMessage = new MailMessage();
                myMessage.From = new MailAddress("noreply@somewhere.com", "Online Alert System");
                myMessage.To.Add(new MailAddress("someone@somewhere.com"));
                myMessage.Subject = "Test Mail";
                myMessage.Body = "This is test mail from OAS.";
                myMessage.IsBodyHtml = true;


                SmtpClient mySmtpClient = new SmtpClient();
                mySmtpClient.Host="smtp.gmail.com";
                mySmtpClient.Port= 587;
                mySmtpClient.Credentials = new NetworkCredential("noreply@somewhere.com", "password");
                mySmtpClient.EnableSsl = true;
                mySmtpClient.Send(myMessage);
            }

            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

        }

但我想使用寡妇服务来做到这一点。请解释我该怎么做。在这种情况下,我对 Windows 服务知之甚少。

提前致谢..!

4

1 回答 1

0
 // try the following code  
 //in app.config add the following key
 // <add key="starttime" value="00.00"/>
    public static System.Timers.Timer Timer;
     Double _timeinterval;
    public static bool IstimerEnabled = false;
      protected override void OnStart(string[] args)
    {
        try
        {
            Timer = new System.Timers.Timer();
            string starttime = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["starttime"]);
           double mins = Convert.ToDouble(starttime);
            DateTime t = DateTime.Now.Date.AddHours(mins); 
            TimeSpan ts = new TimeSpan();
           ts = t.AddDays(1) - System.DateTime.Now;
            log.WriteEntry("BBPush Service timespan ts--" + ts.ToString());
            if (ts.TotalMilliseconds < 0)
            {
               ts = t.AddDays(1) - System.DateTime.Now;
            }
            _timeinterval = ts.TotalMilliseconds;
           Timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            Timer.Interval = _timeinterval;
            Timer.Enabled = true;

        }
        catch (Exception ex)
        {
            log.WriteEntry("exception :" + ex.ToString());

        }
        finally
        {
            IstimerEnabled = false;
            Timer.Start();
        }
    }
    protected override void OnStop()
    {
        Timer.Stop();
        Timer.Dispose();

    }
    private void OnTimedEvent(object source, ElapsedEventArgs e)
    {

       // write your code here or call the method that checks the current date with dob in your table ,fetch the matching emailid and call the mail sending method. 
      //after this method timer is set for 24 hrs.
        Timer.Interval = 86400000;
    }
于 2012-10-16T11:03:52.820 回答