asp.net发送邮件根据类别定时分别发送不同的人,用到Net.Mail类,代码怎...
发布网友
发布时间:2022-04-29 07:44
我来回答
共1个回答
热心网友
时间:2022-04-27 09:55
使用发送定时邮件的功能,但是这个定时发送邮件功能是怎么实现的呢?下面用两种方式实现.net定时发送邮件代码,具体请看下面内容。
实现思路、需求添加一个全局应用程序类Global.asax
代码会在访问网站时运行
Global.asax代码:
void Application_Start(object sender, EventArgs e)
{
// 在应用程序启动时运行的代码
System.Timers.Timer timer = new System.Timers.Timer();//设计时间间隔,如果一个小时执行一次就改为
timer.Elapsed += new System.Timers.ElapsedEventHandler(Send);
timer.AutoReset = true;
timer.Enabled = true;
}
void Application_End(object sender, EventArgs e)
{
// 在应用程序关闭时运行的代码
System.Threading.Thread.Sleep();
string strUrl = "服务器地址";
System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strUrl);
System.Net.HttpWebResponse _HttpWebResponse = (System.Net.HttpWebResponse)_HttpWebRequest.GetResponse();
System.IO.Stream _Stream = _HttpWebResponse.GetResponseStream();//得到回写的字节流
_HttpWebResponse.Close();
}
void Application_Error(object sender, EventArgs e)
{
// 在出现未处理的错误时运行的代码
}
void Session_Start(object sender, EventArgs e)
{
// 在新会话启动时运行的代码
}
void Session_End(object sender, EventArgs e)
{
// 在会话结束时运行的代码。
// 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
// InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer
// 或 SQLServer,则不引发该事件。
}
private void Send(object sender, System.Timers.ElapsedEventArgs e)
{
switch (DateTime.Now.Hour)
{
case :
case :
SendEMail();
break;
//default:
// SendEMail();
// break;
}
}
private void SendEMail()
{
string mailFrom = System.Configuration.ConfigurationManager.AppSettings["MailFrom"].ToString();
string mailUser = System.Configuration.ConfigurationManager.AppSettings["MailUser"].ToString();
string mailPassword = System.Configuration.ConfigurationManager.AppSettings["MailPassword"].ToString();
string hostIP = System.Configuration.ConfigurationManager.AppSettings["MailHost"].ToString();
List<string> mailAddress = new List<string>();
string mailSubjct = "邮件主题";
string mailBody = "邮件内容:";
mailAddress.Add("邮件地址");string strReturn = sendMail(mailSubjct, mailBody, mailFrom, mailAddress, hostIP, mailUser, mailPassword, false);
}
sendMail方法
public static string sendMail(string mailSubjct, string mailBody, string mailFrom, List<string> mailAddress, string hostIP, string username, string password, bool ssl)
{
string str = "";
try
{
MailMessage message = new MailMessage
{
IsBodyHtml = true,
Subject = mailSubjct,
Body = mailBody,
From = new MailAddress(mailFrom)
};
for (int i = ; i < mailAddress.Count; i++)
{
message.To.Add(mailAddress[i]);
}
SmtpClient client = new SmtpClient
{
EnableSsl = ssl,
UseDefaultCredentials = false
};
NetworkCredential credential = new NetworkCredential(username, password);
client.Credentials = credential;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Host = hostIP;
client.Port = x;
client.Send(message);
}
catch (Exception exception)
{
str = exception.Message;
}
return str;
}