C# 多线线程邮件发送Windows服务

  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.ComponentModel;   
  4. using System.Configuration.Install;   
  5. using System.ServiceProcess;   
  6. using System.Collections;   
  7. using System.Threading;   
  8. using System.Xml;   
  9. using System.IO;   
  10. using System.Net.Mail;   
  11. using System.Runtime.Remoting.Channels.Tcp;   
  12. using System.Runtime.Remoting.Channels;   
  13. using System.Runtime.Remoting;   
  14. using Pub.Class;   
  15. using System.Diagnostics;   
  16.   
  17. namespace MailService {   
  18.   
  19.     [RunInstaller(true)]   
  20.     public partial class MService : ServiceBase {   
  21.         public static bool isRun = false;   
  22.         public Queue emailQueue = new Queue();   
  23.         private Thread readEmailThread;   
  24.         private Thread[] sendEmailThread;   
  25.         private string[] strList = new string[] { "MailService 启动成功!""MailService 停止!""{2} {1} - [{0}] - 发送失败!""{2} {1} - [{0}] - 发送成功!""LiveRemotingService 已启动,服务端口6669。""LiveRemotingService 停止!" };   
  26.   
  27.         private struct Config {                                                                                                                                                                                                                                        
  28.             public string Conn;   
  29.             public string LogFile;   
  30.             public string SmtpServer;   
  31.             public string UserName;   
  32.             public string Password;   
  33.             public string FromAddress;   
  34.             public int AmountThread;   
  35.             public int RecordCount;   
  36.             public int TimeInterval;   
  37.         }   
  38.         private Config config = new Config();   
  39.   
  40.         public MService() {   
  41.             System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;   
  42.             InitializeComponent();   
  43.   
  44.             if (!System.Diagnostics.EventLog.SourceExists("MailSource")) System.Diagnostics.EventLog.CreateEventSource("MailSource""MailServiceLog");   
  45.             this.eventLog1.Source = "MailSource";   
  46.             this.eventLog1.Log = "MailServiceLog";   
  47.             this.eventLog2.Source = "LiveRemotingSource";   
  48.             this.eventLog2.Log = "MailServiceLog";   
  49.         }   
  50.   
  51.         protected override void OnStart(string[] args) {   
  52.             try {   
  53.                 InitConfig();   
  54.                 this.eventLog1.WriteEntry(strList[0], System.Diagnostics.EventLogEntryType.SuccessAudit);   
  55.   
  56.                 this.timer1.Interval = config.TimeInterval * 1000;   
  57.                 this.timer1.Enabled = true;   
  58.                 sendEmailThread = new Thread[config.AmountThread];   
  59.             } catch (Exception e) {   
  60.                 this.eventLog1.WriteEntry(e.ToString(), System.Diagnostics.EventLogEntryType.Error);   
  61.             }   
  62.         }   
  63.   
  64.         protected override void OnStop() {   
  65.             this.eventLog1.WriteEntry(strList[1], System.Diagnostics.EventLogEntryType.SuccessAudit);   
  66.             GC.Collect();   
  67.             this.timer1.Enabled = false;   
  68.         }   
  69.   
  70.         private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {   
  71.             if (isRun) return;   
  72.   
  73.             timer1.Enabled = false;   
  74.             readEmailThread = new Thread(new ThreadStart(ReadEmailQuque));    
  75.             readEmailThread.IsBackground = true;   
  76.             readEmailThread.Start();   
  77.         }   
  78.   
  79.         private void InitConfig(){   
  80.             config.Conn = Pub.Class.WebConfig.GetApp("ConnString");   
  81.             config.LogFile = Pub.Class.WebConfig.GetApp("logFile");   
  82.             config.SmtpServer = Pub.Class.WebConfig.GetApp("SmtpServer");   
  83.             config.UserName = Pub.Class.WebConfig.GetApp("UserName");   
  84.             config.Password = Pub.Class.WebConfig.GetApp("Password");   
  85.             config.FromAddress = Pub.Class.WebConfig.GetApp("FromAddress");   
  86.             string amountThread = Pub.Class.WebConfig.GetApp("AmountThread");   
  87.             config.AmountThread = amountThread.Equals("") ? 1 : Convert.ToInt32(amountThread);   
  88.             config.AmountThread = config.AmountThread < 1 ? 1 : config.AmountThread;   
  89.             string recordCount = Pub.Class.WebConfig.GetApp("RecordCount");   
  90.             config.RecordCount = recordCount.Equals("") ? 1000 : Convert.ToInt32(recordCount);   
  91.             config.RecordCount = config.RecordCount < 1000 ? 1000 : config.RecordCount;   
  92.             string timeInterval = Pub.Class.WebConfig.GetApp("TimeInterval");   
  93.             config.TimeInterval = timeInterval.Equals("") ? 1000 : Convert.ToInt32(timeInterval);   
  94.             config.TimeInterval = config.TimeInterval < 2 ? 2 : config.TimeInterval;   
  95.         }   
  96.   
  97.         private void ReadEmailQuque(){   
  98.             timer1.Enabled = true;   
  99.             IList<EC_EmailList> list = EC_EmailListFactory.Instance().SelectListByTop(config.RecordCount);   
  100.             if (list.Count == 0) return;   
  101.   
  102.             isRun = true;   
  103.             for (int i = 0; i < list.Count; i++) {   
  104.                 emailQueue.Enqueue(list[i]);   
  105.             }   
  106.   
  107.             for (int i = 0; i < config.AmountThread; i++) {   
  108.                 sendEmailThread[i] = new Thread(new ThreadStart(DoSendEmail));   
  109.                 sendEmailThread[i].Name = "Thread" + (i+1).ToString();   
  110.                 sendEmailThread[i].Start();   
  111.             }   
  112.             list = null;   
  113.         }   
  114.   
  115.         private void DoSendEmail(){   
  116.             while (true) {   
  117.                 EC_EmailList objMail;   
  118.                 lock(this){   
  119.                     if (emailQueue.Count>0) {   
  120.                         objMail = (EC_EmailList)emailQueue.Dequeue();   
  121.                     } else {   
  122.                         isRun = false;   
  123.                         return;   
  124.                     }   
  125.                 }   
  126.   
  127.                 int mailID = (int)objMail.EmailID;   
  128.                 string strTo = objMail.To;   
  129.                 string strSubject = objMail.Subject;   
  130.                 string strBody = objMail.Body;   
  131.                 string strFrom = objMail.From;   
  132.                 string smtpServer = objMail.SmtpServer;   
  133.                 string userName = objMail.UserName;   
  134.                 string password = objMail.Password;   
  135.   
  136.                 bool isTrue = SendMail(strTo, strSubject, strBody, strFrom, smtpServer, userName, password, "");   
  137.   
  138.                 EC_EmailListFactory.Instance().DeleteByID(mailID);   
  139.   
  140.             }   
  141.         }   
  142.   
  143.         public bool SendMail(string strTo, string strSubject, string strBody,   
  144.                              string strFrom, string smtpServer, string userName,   
  145.                              string password, string attachments) {   
  146.             Email email = new Email();   
  147.             string strSmtpServer = smtpServer.Length > 0 ? smtpServer : config.SmtpServer.Trim();   
  148.             email.SmtpServer = strSmtpServer;   
  149.             email.SmtpUserName = userName.Length > 0 ? userName : config.UserName.Trim();   
  150.             email.SmtpPassword = password.Length > 0 ? password : config.Password.Trim();   
  151.             email.SmtpPort = strSmtpServer.ToLower().Contains("gmail") ? "587" : "25";   
  152.             email.EnableSsl = strSmtpServer.ToLower().Contains("gmail") ? true : false;   
  153.             email.FromEmail = strFrom.Length > 0 ? strFrom : config.FromAddress.Trim();   
  154.             email.Subject = strSubject;   
  155.             email.Body = strBody;   
  156.             email.Encoding = System.Text.Encoding.UTF8;   
  157.             bool isSuccess = email.SmtpClientSend(strTo);   
  158.             return isSuccess;   
  159.         }   
  160.         public void ErrorLog(string strMessage) {   
  161.             lock(this){   
  162.                 StreamWriter sw = new StreamWriter(config.LogFile + "MailLog.txt"true);   
  163.                 sw.WriteLine(strMessage);   
  164.                 sw.Flush();   
  165.                 sw.Close();   
  166.             }   
  167.         }   
  168.     }   
  169. }  
posted @ 2012-02-23 18:52  therockthe  阅读(305)  评论(0)    收藏  举报