C#應用體系辦法發送異步郵件完全實例。本站提示廣大學習愛好者:(C#應用體系辦法發送異步郵件完全實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#應用體系辦法發送異步郵件完全實例正文
本文實例講述了C#應用體系辦法發送異步郵件。分享給年夜家供年夜家參考,詳細以下:
項目配景:
比來在對幾年前的一個項目停止重構,發明發送郵件功效須要必定的時光來處置,而因為發送是同步的是以招致在發送郵件時沒法履行後續的操作
現實上發送郵件後只須要將發送成果寫入體系日記便可對其他營業沒有任何影響,是以決議將發送郵件操作更改成異步的
因為應用的是C#的郵件類庫,而C#自己曾經供給了異步發送的功效即只須要將Send辦法更改成SendAsync便可,更改辦法名其實不難但發送後再寫入日記就有點難了
由於項目中發送郵件是零丁的組件,所以我弗成能在發送郵件類庫中直接添加寫入日記操作(不在統一個類庫,收集和MSDN上的例子都是統一組件下)
但C#可使用拜托將辦法作為參數來傳遞的,是以我便可以在發送郵件的辦法中添加一個回調辦法,在異步發送郵件後再履行回調辦法便可
完全代碼:
/****************************************************************** * 創立人:HTL * 解釋:C# 發送異步郵件Demo *******************************************************************/ using System; using System.Net.Mail; namespace SendAsyncEmailTest { class Program { const string dateFormat = "yyyy-MM-dd :HH:mm:ss:ffffff"; static void Main(string[] args) { Console.WriteLine("開端異步發送郵件,時光:" + DateTime.Now.ToString(dateFormat)); new MailHelper().SendAsync("Send Async Email Test", "This is Send Async Email Test", "[email protected]", emailCompleted); Console.WriteLine("郵件正在異步發送,時光:" + DateTime.Now.ToString(dateFormat)); Console.ReadKey(); Console.WriteLine(); } /// <summary> /// 郵件發送後的回調辦法 /// </summary> /// <param name="message"></param> static void emailCompleted(string message) { //延時1秒 System.Threading.Thread.Sleep(1000); Console.WriteLine(); Console.WriteLine("郵件發送成果:\r\n" + (message == "true" ? "郵件發送勝利" : "郵件發送掉敗") + ",時光:" + DateTime.Now.ToString(dateFormat)); //寫入日記 } } /// <summary> /// 發送郵件類 /// </summary> public class MailHelper { public delegate int MethodDelegate(int x, int y); private readonly int smtpPort = 25; readonly string SmtpServer = "smtp.百度.com"; private readonly string UserName = "support@百度.com"; readonly string Pwd = "百度.com"; private readonly string AuthorName = "BaiDu"; public string Subject { get; set; } public string Body { get; set; } public string Tos { get; set; } public bool EnableSsl { get; set; } MailMessage GetClient { get { if (string.IsNullOrEmpty(Tos)) return null; MailMessage mailMessage = new MailMessage(); //多個吸收者 foreach (string _str in Tos.Split(',')) { mailMessage.To.Add(_str); } mailMessage.From = new System.Net.Mail.MailAddress(UserName, AuthorName); mailMessage.Subject = Subject; mailMessage.Body = Body; mailMessage.IsBodyHtml = true; mailMessage.BodyEncoding = System.Text.Encoding.UTF8; mailMessage.SubjectEncoding = System.Text.Encoding.UTF8; mailMessage.Priority = System.Net.Mail.MailPriority.High; return mailMessage; } } SmtpClient GetSmtpClient { get { return new SmtpClient { UseDefaultCredentials = false, Credentials = new System.Net.NetworkCredential(UserName, Pwd), DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network, Host = SmtpServer, Port = smtpPort, EnableSsl = EnableSsl, }; } } //回調辦法 Action<string> actionSendCompletedCallback = null; ///// <summary> ///// 應用異步發送郵件 ///// </summary> ///// <param name="subject">主題</param> ///// <param name="body">內容</param> ///// <param name="to">吸收者,以,分隔多個吸收者</param> //// <param name="_actinCompletedCallback">郵件發送後的回調辦法</param> ///// <returns></returns> public void SendAsync(string subject, string body, string to, Action<string> _actinCompletedCallback) { if (string.IsNullOrEmpty(to)) return; Tos = to; SmtpClient smtpClient = GetSmtpClient; MailMessage mailMessage = GetClient; if (smtpClient == null || mailMessage == null) return; Subject = subject; Body = body; EnableSsl = false; //發送郵件回調辦法 actionSendCompletedCallback = _actinCompletedCallback; smtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); try { smtpClient.SendAsync(mailMessage, "true");//異步發送郵件,假如回調辦法中參數不為"true"則表現發送掉敗 } catch (Exception e) { throw new Exception(e.Message); } finally { smtpClient = null; mailMessage = null; } } /// <summary> /// 異步操作完成後履行回調辦法 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SendCompletedCallback(object sender, System.ComponentModel.AsyncCompletedEventArgs e) { //統一組件下不須要回調辦法,直接在此寫入日記便可 //寫入日記 //return; if (actionSendCompletedCallback == null) return; string message = string.Empty; if (e.Cancelled) { message = "異步操作撤消"; } else if (e.Error != null) { message = (string.Format("UserState:{0},Message:{1}", (string)e.UserState, e.Error.ToString())); } else message = (string)e.UserState; //履行回調辦法 actionSendCompletedCallback(message); } } }
運轉後果圖以下:
願望本文所述對年夜家C#法式設計有所贊助。