标签:
最近在对几年前的一个项目进行重构,发现发送邮件功能需要一定的时间来处理,而由于发送是同步的因此导致在发送邮件时无法执行后续的操作
/****************************************************************** * 创建人:HTL * 创建时间:2015-04-16 21:34:25 * 说明:C# 发送异步邮件Demo * Email:huangyuan413026@163.com *******************************************************************/ 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", "huangyuan413026@163.com", 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.xxxx.cn"; private readonly string UserName = "support@xxx.cn"; readonly string Pwd = "123456"; private readonly string AuthorName = "HTL"; public string Subject { get; set; } public string Body { get; set; } public string[] Tos { get; set; } public bool EnableSsl { get; set; } MailMessage GetClient { get { if (Tos == null) return null; MailMessage mailMessage = new MailMessage(); //多个接收者 foreach (string str in Tos) { foreach (string _str in str.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; Subject = subject; Body = body; Tos = to.Split(‘,‘); EnableSsl = false; SmtpClient smtpClient = GetSmtpClient; //发送邮件回调方法 actionSendCompletedCallback = _actinCompletedCallback; smtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback); MailMessage mailMessage = GetClient; 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); } } }
标签:
原文地址:http://www.cnblogs.com/huangtailang/p/4433457.html