Asp.Net 如何定时发送邮件
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);
}
}
}
留言列表: