本文實例講述了asp.net基于windows服務實現定時發送郵件的方法。分享給大家供大家參考,具體如下:
- //定義組件
- private System.Timers.Timer time;
- public int nowhour;
- public int minutes;
- public string sendTime;
- public Thread th;
- public string isOpen;//是否啟用定時發送
- public string strToEUser;
- public static int index = -1;
- public static ArrayList mulitaddress;
- //服務開始
- protected override void OnStart(string[] args)
- {
- time = new System.Timers.Timer();
- time.Enabled = true;
- time.AutoReset = true;
- //定時執行方法
- time.Elapsed+=new System.Timers.ElapsedEventHandler(time_Elapsed);
- UserEmail toUser =new UserEmail();
- mulitaddress = GetMailAdressName();
- // LogHelper.SaveNote("當前索引的值" + index.ToString());
- Thread.Sleep(2000);
- time.Start();
- }
- public class LogHelper
- {
- public static void SaveNote(string note)
- {
- FileStream stream = new FileStream(GetLogDirectory("Common") + DateTime.Now.ToString("yyyy-MM-dd") + ".txt", FileMode.Append, FileAccess.Write, FileShare.Delete | FileShare.ReadWrite);
- StreamWriter writer = new StreamWriter(stream, Encoding.UTF8);
- writer.WriteLine("================================================================");
- writer.WriteLine(string.Format("Note:/t{0}", note));
- writer.WriteLine(string.Format("DateTime:/t{0}/r/n/r/n",DateTime.Now.ToString()));
- stream.Flush();
- writer.Close();
- stream.Close();
- stream.Dispose();
- writer.Dispose();
- }
- public static void SaveNote(string note, string txtname)
- {
- FileStream stream = new FileStream(GetLogDirectory(txtname) + DateTime.Now.ToString("yyyy-MM-dd") + ".txt", FileMode.Append, FileAccess.Write, FileShare.Delete | FileShare.ReadWrite);
- StreamWriter writer = new StreamWriter(stream, Encoding.GetEncoding("gb2312"));
- writer.WriteLine("================================================================");
- writer.WriteLine(string.Format("Note:/t{0}", note));
- writer.WriteLine(string.Format("DateTime:/t{0}/r/n/r/n", DateTime.Now.ToString("yyyyMMddHHmmss")));
- stream.Flush();
- writer.Close();
- stream.Close();
- stream.Dispose();
- writer.Dispose();
- }
- public static void SaveException(Exception e)
- {
- SaveException(e, string.Empty);
- }
- public static void SaveException(Exception e, string memo)
- {
- FileStream stream = new FileStream(GetLogDirectory("Common") + DateTime.Now.ToString("yyyy-MM-dd") + ".txt", FileMode.Append, FileAccess.Write, FileShare.Delete | FileShare.ReadWrite);
- StreamWriter writer = new StreamWriter(stream);
- writer.WriteLine("================================================================");
- writer.WriteLine(string.Format("Memo:/t{0}", memo));
- writer.WriteLine(string.Format("DateTime:/t{0}", DateTime.Now.ToShortTimeString()));
- writer.WriteLine(string.Format("Message:/t{0}", e.Message));
- writer.WriteLine(string.Format("StackTrace:/r/n----------/r/n{0}/r/n----------/r/n/r/n/r/n", e.StackTrace));
- stream.Flush();
- writer.Close();
- stream.Close();
- stream.Dispose();
- writer.Dispose();
- }
- public static string GetLogDirectory(string category)
- {
- string baseDirectory = string.Empty;
- if ((HttpContext.Current != null) && (HttpContext.Current.Server != null))
- {
- baseDirectory = HttpContext.Current.Server.MapPath("~");
- }
- else
- {
- baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
- }
- if ((baseDirectory[baseDirectory.Length - 1] != '/') && (baseDirectory[baseDirectory.Length - 1] != '//'))
- {
- baseDirectory = baseDirectory + @"/";
- }
- baseDirectory = string.Format(@"{0}Log/{1}/", baseDirectory, category);
- if (!Directory.Exists(baseDirectory))
- {
- Directory.CreateDirectory(baseDirectory);
- }
- return baseDirectory;
- }
- }
- void time_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
- {
- try
- {
- if (mulitaddress != null)
- {
- LogHelper.SaveNote("進入time_Elapsed");
- //獲取定時發送時間
- sendTime = Convert.ToString(GetConfigValue("sendTime"));
- LogHelper.SaveNote("sendTime" + sendTime);
- //是否開啟定時發送功能
- isOpen = GetConfigValue("isOpen");
- int sleeptime = Convert.ToInt32(GetConfigValue("SleepTime"));
- int stoptime = Convert.ToInt32(GetConfigValue("stoptime"));
- //LogHelper.SaveNote("數組長度" + mulitaddress.Count);
- // LogHelper.SaveNote("是否開啟定時發送功能" + isOpen + "定時時間" + sendTime + "定時小時數:" + Convert.ToInt32(sendTime.Split(new char[] { ':' })[0]) + "定時分鐘數:" + Convert.ToInt32(sendTime.Split(new char[] { ':' })[1]));
- if (isOpen == "true")
- {
- //現在時間 小時
- nowhour = Convert.ToInt32(DateTime.Now.Hour.ToString());//10
- //現在分鐘
- minutes = Convert.ToInt32(DateTime.Now.Minute.ToString());//5
- //獲取發送小時
- int sendhour = Convert.ToInt32(sendTime.Split(new char[] { ':' })[0]);
- //獲取發送的分鐘
- int sendMinute = Convert.ToInt32(sendTime.Split(new char[] { ':' })[1]);
- LogHelper.SaveNote("進入定時發送郵件服務! 定時小時為:" + sendhour.ToString() + "定時分鐘為:" + sendMinute.ToString() + "現在小時為:" + nowhour.ToString() + "現在定時的分鐘為:" + minutes.ToString());
- LogHelper.SaveNote("當前索引的值" + index.ToString());
- if (nowhour == stoptime)
- {
- LogHelper.SaveNote("停止時間點到了 郵件停止發送 ?。?!");
- index = -1;
- }
- else
- {
- //如果和當前的時間 小時相等 則定時發送郵件
- if ((Convert.ToDateTime(DateTime.Now.ToShortTimeString()) >= Convert.ToDateTime(sendTime)) && index < mulitaddress.Count)
- {
- index++;
- if (index < mulitaddress.Count)
- {
- SendEmail(((UserEmail)mulitaddress[index]));
- }
- else
- {
- LogHelper.SaveNote("發送完畢 當前的索引值為" + index.ToString());
- }
- }
- }
- }
- else
- {
- //LogHelper.SaveNote("當前索引的值" + index.ToString());
- index++;
- if (index < mulitaddress.Count)
- {
- SendEmail(((UserEmail)mulitaddress[index]));
- }
- else
- {
- LogHelper.SaveNote("發送完畢 時間停止");
- time.Enabled = false;
- time.Stop();
- }
- }
- Thread.Sleep(sleeptime);
- }
- else
- LogHelper.SaveNote("mulitaddress=null");
- }
- catch (Exception ex)
- {
- LogHelper.SaveNote(ex.ToString());
- }
- }
- public ArrayList GetMailAdressName()
- {
- ArrayList list = new ArrayList();
- string strSQL = "select b.mailAddress, a.mailtemplate,a.title from tg_product as a inner join tg_mailOrder as b on a.ccode=b.ccode where a.createtime=(select max(createtime) from tg_product)";
- SqlDataReader dr = SqlHelper.ExecuteReader(CommandType.Text, strSQL, null);
- if (dr.HasRows)
- {
- while (dr.Read())
- {
- UserEmail email = new UserEmail();
- email.Mailaddres = dr["mailAddress"].ToString();
- email.Title = dr["title"].ToString();
- email.Contents = dr["mailtemplate"].ToString();
- list.Add(email);
- }
- }
- return list;
- }
- /// <summary>
- /// 定義用戶郵件 標題 內容 Email地址
- /// </summary>
- public class UserEmail {
- private string title;
- private string contents;
- public string Contents
- {
- get { return contents; }
- set { contents = value; }
- }
- private string mailaddres;
- public string Mailaddres
- {
- get { return mailaddres; }
- set { mailaddres = value; }
- }
- public string Title {
- get{return title;}
- set { title = value; }
- }
- }
- #region 發送郵件
- /// <summary>
- /// 發送郵件
- /// </summary>
- public void SendEmail(UserEmail user)
- {
- try
- {
- LogHelper.SaveNote("進入SendEmail!!!");
- //郵件服務器
- string smtpserver = GetConfigValue("smtpserver");
- //發件人的郵箱名稱
- string emailuserName = GetConfigValue("emailuserName");
- //發件人的郵箱密碼
- string emailuserpwd = GetConfigValue("emailuserpwd");
- //郵箱地址
- string emailfrom = GetConfigValue("emailfrom");
- int port = Convert.ToInt32(GetConfigValue("serverPort"));
- bool f = true;
- //是否經過SSL加密
- string isSSL = GetConfigValue("SSL");
- if (isSSL == "true")
- {
- f = true;
- }
- else
- {
- f = false;
- }
- LogHelper.SaveNote("發件人的郵箱名稱" + emailuserName + "郵件地址(emailFrom)" + emailfrom + "收件人" + user.Mailaddres);
- SendEmailToUser(smtpserver, port, f, user.Mailaddres, null, emailuserName, emailuserpwd, emailfrom, user.Title,user.Contents);
- LogHelper.SaveNote("Send Mail Success");
- }
- //獲取異常信息
- catch (Exception error)
- {
- //寫入異常信息
- using (StreamWriter sw = new StreamWriter("F://MailErrorlog.txt", true, System.Text.Encoding.UTF8))
- {
- sw.WriteLine(DateTime.Now.ToString() + ":");
- sw.WriteLine("Exception 異常信息如下.................");
- sw.WriteLine(error.ToString());
- sw.WriteLine("---------------------------------------------");
- sw.Close();
- }
- }
- }
- #endregion
- #region 利用.Net自帶類(SmtpClient) 發送郵件
- /// <summary>
- /// 利用.Net自帶類(SmtpClient) 發送郵件
- /// </summary>
- /// <param name="stmpserver">郵件服務器</param>
- /// <param name="username">用戶名(郵箱名稱)</param>
- /// <param name="pwd">密碼</param>
- /// <param name="f">是否經過SSL加密</param>
- /// <param name="port">郵件服務器端口(沒有加密 一般都是25)</param>
- /// <param name="strfrom">發件人</param>
- /// <param name="strto">收件人</param>
- /// <param name="subject">主題</param>
- /// <param name="body">內容</param>
- /// <param name="Mulitaddress">發送多人 收件人的郵箱地址以逗號隔開</param>
- /// <param name="attachmentName">發送的附件名稱 沒有附件則為null or ""</param>
- public void SendEmailToUser(string stmpserver,int port,bool f, string Mulitaddress, string attachmentName, string username, string pwd, string strfrom, string subject, string body)
- {
- string ErrorLog = GetConfigValue("ErrorLog");
- SmtpClient smtp = new SmtpClient();
- //發送郵件的方式
- smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
- //指定郵件服務器
- smtp.Host = stmpserver;
- //Gmail QQ stmp ssl加密使用的端口
- smtp.Port = port;
- smtp.EnableSsl = f; ;//true 經過ssl加密
- //驗證發件人的身份 用戶名(郵件地址和密碼)
- smtp.Credentials = new System.Net.NetworkCredential(username, pwd);
- //初始化信息(來自 接收人)
- MailMessage _mailmessage = new MailMessage();
- //_mailmessage.To = strto;
- //發送多個人 接收人郵件地址以,隔開
- _mailmessage.From = new MailAddress(strfrom);
- _mailmessage.To.Add(Mulitaddress);
- //如果發送失敗,SMTP 服務器將發送 失敗郵件通知
- _mailmessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
- //優先級
- _mailmessage.Priority = MailPriority.High;
- //發送主題
- _mailmessage.Subject = subject;
- //有附件則添加附件
- if (!string.IsNullOrEmpty(attachmentName))
- {
- System.Net.Mail.Attachment attch = new System.Net.Mail.Attachment(attachmentName);
- _mailmessage.Attachments.Add(attch);
- }
- //郵件主題編碼
- _mailmessage.SubjectEncoding = System.Text.Encoding.UTF8;
- //指定發送的格式 (Html)
- _mailmessage.IsBodyHtml = true;
- //指定發送郵件的編碼
- _mailmessage.BodyEncoding = System.Text.Encoding.UTF8;
- //指定郵件內容
- _mailmessage.Body = body;
- //發送郵件
- try
- {
- smtp.Send(_mailmessage);
- }
- catch (Exception ex)
- {
- using (StreamWriter writer = new StreamWriter(ErrorLog+"://MailErrorlog.txt", true, System.Text.Encoding.UTF8))
- {
- writer.WriteLine("---------------------------------------------");
- writer.WriteLine("SendEmail方法發送郵件錯誤日志................");
- writer.WriteLine(ex.ToString());
- writer.Flush();
- writer.Close();
- }
- }
- }
- #endregion
- #region 獲取郵件配置節點的值
- /// <summary>
- /// 加載相應配置文件 并按節點名稱獲取對應的值
- /// </summary>
- /// <param name="target">當前節點的名稱</param>
- /// <returns>返回當前節點名稱所對應的值</returns>
- public string GetConfigValue(string target)
- {
- string configpath=System.Windows.Forms.Application.StartupPath.ToString() + "/Email.config";
- return GetConfigValue(configpath, target);
- }
- /// <summary>
- /// 根據節點名稱獲取配置文件對應的值(郵件配置信息)
- /// </summary>
- /// <param name="configpath">配置文件路徑</param>
- /// <param name="target">要獲取配置節點的名稱</param>
- /// <returns>返回當前節點名稱所對應的值</returns>
- public string GetConfigValue(string configpath, string target)
- {
- XmlDocument doc = new XmlDocument();
- //加載文件路徑s
- doc.Load(configpath);
- //獲取當前節點的根節點
- XmlElement root = doc.DocumentElement;
- //獲取當前節點下所有匹配子節點元素
- XmlNodeList xmlnode = root.GetElementsByTagName(target);
- //返回值
- return xmlnode[0].InnerXml;
- }
- #endregion
- //服務結束
- protected override void OnStop()
- {
- time.Enabled = false;
- }
新聞熱點
疑難解答
圖片精選