使用windows服务定时发送email核心代码
public partial class Service1 : ServiceBase
{
private Thread _thread;
private bool StopThreads = false;
private bool HasSentMail = false;
public Service1()
{
InitializeComponent();
try
{
_thread = new Thread(new ThreadStart(sendmail));
}
catch (Exception e)
{ }
}
protected override void OnStart(string[] args)
{
_thread.Start();
}
protected override void OnStop()
{
// TODO: 在此处添加代码以执行停止服务所需的关闭操作。
StopThreads = true;
RunLog.WriteLog("Service stop at:");
}
private void sendmail()
{
RunLog.WriteLog("Service start at:");
while (!StopThreads)
{
if (DateTime.Now.Day==28 && DateTime.Now.Hour==9 && DateTime.Now.Minute<=10 && HasSentMail==false)
{
MailMessage mm;
mm = new MailMessage();
StringBuilder ensb = new StringBuilder();
StringBuilder cnsb = new StringBuilder();
mm.From = new MailAddress("abc@domain.com");
mm.Subject = "Test";
mm.BodyEncoding = System.Text.Encoding.UTF8;
mm.BodyEncoding =Encoding.UTF8;
mm.IsBodyHtml=true;
DataSet ds = sgbox_namelistDac.GetList();
SmtpClient sc = new SmtpClient("smtp.domain.com");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
mm.Body = "<htmp><body><font size=2 face='Arial, Helvetica, sans-serif'>Dear Supplier </font>" + ensb.ToString() + "<font size=2 face='Arial, Helvetica, sans-serif'>尊敬的供应商 " + cnsb.ToString();
mm.To.Clear();
mm.To.Add(new MailAddress(ds.Tables[0].Rows[i]["email"].ToString().Trim()));
try
{
sc.Send(mm);
RunLog.WriteLog("Sent at:");
}
catch (Exception e)
{
RunLog.WriteLog("SMTP发送失败:" + e.Message);
return;
}
Thread.Sleep(3000);
}
HasSentMail = true;
}
else
{
HasSentMail = false;
}
Thread.Sleep(600000);
}
}
}