16
2012
04

Asp.Net 如何定时发送邮件

一般邮件定时发送是使用Winform来实现比较简单,但在 ASP.NET中也可以使用计时器(Timer)完成一些定时动作。做一个winform 来定时发邮件。然后通过windows计划任务,设置为指定时间,每次自动运行,运行完毕后自动关闭。而Asp.net中也使用Timer 设定间隔多长时间执行发送事件
  protected void Application_Start(Object sender, EventArgs e)
  {
  Timer t = new Timer(60000);//设计时间间隔,如果一个小时执行一次就改为3600000 ,这里一分钟调用一次
  t.Elapsed = new ElapsedEventHandler(t_Elapsed); //间隔一分钟后执行t_Elapsed事件
  t.AutoReset = true;
  t.Enabled = true;
  }

  private void t_Elapsed(object sender, ElapsedEventArgs e)
  {
  if (GetEmailContent.GetMailContent().Length == 0) //判断邮件内容是否为空,为空返回不发送,或者如果数据库中设置了发送时间,那么就判断发送的时间是否大于当前时间,大于的话就是还没有到时间,就不用发送
  {
  return;//则返回不发送邮件
  }

  int sendTime_Hour = Convert.ToInt32(ConfigurationManager.AppSettings["SendTime"].ToString());// 可以自己设置发送时间
  int now_Hour = Convert.ToInt32(DateTime.Now.Hour.ToString());
  int now_Minute = Convert.ToInt32(DateTime.Now.Minute.ToString());
  int absolute = 1;//差距值,单位为分钟
  if (((now_Hour == sendTime_Hour - 1) && (now_Minute >= 60 - absolute)) || ((now_Hour == sendTime_Hour) && (now_Minute <= absolute))) //即在如果时间判断在发送时间之间,那么就会调用下面的邮件发送方法
  {
  string subject = string.Format("CO Approve Report({0})", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
  string host = ConfigurationManager.AppSettings["MailHost"]; //设置发送的邮件配置和发送内容
  string from = ConfigurationManager.AppSettings["MailFrom"];
  string to = ConfigurationManager.AppSettings["MailTo"];
  string user = ConfigurationManager.AppSettings["MailUser"];
  string password = ConfigurationManager.AppSettings["MailPassword"];
  string content = GetEmailContent.GetMailContent();
  try
  {
  OrderMail.Send(host, user, password, to, from, subject, content, null);//发送邮件的方法,改为你自己的邮件发送方法
  }
  catch (Exception ex)
  {
  throw new Exception(ex.Message);
  }
  }
  }
« 上一篇下一篇 »

评论列表:

1.监控安装  2014/12/4 17:08:28 回复该留言
&lt;/br&gt;&lt;a href=&quot;http://www.afvvv.com&quot;&gt;监控安装&lt;/a&gt;&lt;/br&gt;[url=http://www.afvvv.com]监控安装[/url]&lt;/br&gt;http://www.afvvv.com
2.探头安装  2015/1/12 5:24:47 回复该留言
非常,相當之感謝!!</br>http://www.afvvv.com
3.监控安装  2015/1/12 16:08:39 回复该留言
下载看了,感觉非常不错。以后大家有机会多分享啊~~</br>http://www.afvvv.com

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。