Code
1
2 protected override void OnStart(string[] args)
3 {
4 MyTimer();
5 }
6
7 //執行個體化System.Timers.Timer
8 private void MyTimer()
9 {
10 //設定時間間隔
11 System.Timers.Timer MT = new System.Timers.Timer(int.Parse(ConfigResource.Interval)*60*1000);
12 MT.Elapsed += new System.Timers.ElapsedEventHandler(MTimedEvent);
13 MT.Enabled = true;
14
15 }
16 //構造System.Timers.Timer執行個體 間隔時間事件 (定時執行事件)
17 private void MTimedEvent(object source, System.Timers.ElapsedEventArgs e)
18 {
19 //開始工作
20 StartWork();
21 }
22
23 public void StartWork()
24 {
25 //從資料庫DB查詢表A中的時間 代碼省略。。。
26 //時間比較
27 if(
) //時間大于目前系統時間
28 {
29 //發送郵件
30 int iStatus = SendMail("你指定的收件人Email位址","标題","内容");
31 if( iStatus > 0)
32 {
33 using (StreamWriter sw = new StreamWriter(filePath + "log.txt", System.Text.Encoding.GetEncoding("utf-8")))
34 {
35 sw.Wirte(System.DateTime.Now.ToString() + " 發送郵件成功!")
36 }
37 }
38 else{//失敗}
39 }
40 }
41
42 /// <summary>
43 /// 發送EMAIL
44 /// </summary>
45 /// <param name="sRecipientEmail">收件人位址</param>
46 /// <param name="sSubject">主題</param>
47 /// <param name="sMessage">内容</param>
48 /// <returns>發送是否成功</returns>
49 public bool SendMail(string sRecipientEmail, string sSubject, string sMessage)
50 {
51
52 //郵件對象
53 MailMessage emailMessage;
54
55 //smtp用戶端對象
56
57 SmtpClient client;
58
59 // 初始化郵件對象
60
61 String sSenderEmail = "你的郵箱";
62
63 emailMessage = new MailMessage(sSenderEmail, sRecipientEmail, sSubject, sMessage);
64 emailMessage.IsBodyHtml = true;
65 emailMessage.SubjectEncoding = System.Text.Encoding.Default;
66 emailMessage.BodyEncoding = System.Text.Encoding.Default;
67 //加入
68 emailMessage.Headers.Add("X-Priority", "3");
69 emailMessage.Headers.Add("X-MSMail-Priority", "Normal");
70 emailMessage.Headers.Add("X-Mailer", "Microsoft Outlook Express 6.00.2900.2869");
71 emailMessage.Headers.Add("X-MimeOLE", "Produced By Microsoft MimeOLE V6.00.2900.2869");
72
73 //郵件發送用戶端
74 client = new SmtpClient();
75
76 //郵件伺服器及帳戶資訊
77 client.Host = "郵件伺服器";
78 //client.Host = "smtp.163.com";
79
80 //client.Port = 465;
81 //client.EnableSsl = true;
82 System.Net.NetworkCredential Credential = new System.Net.NetworkCredential();
83
84 Credential.UserName = "你的郵箱帳号" //可以在資源檔案中配置
85 Credential.Password = "密碼"
86
87 client.Credentials = Credential;
88
89 try
90 {
91 client.Send(emailMessage);
92 }
93 catch (Exception e)
94 {
95 return false;
96 }
97 return true;
98
99 }
100
101
102