对于邮件发送,一般来说,程序会响应超过1秒,这样对于用户体验来说,让用户等待的时间过长,而且发送的邮件越多时间就越长,所以这里我利用了线程的来处理邮件发送这种耗时的工作,废话不多说,直接上代码
private string title; /// <summary> /// 发送标题 /// </summary> public string Title { get { return title; } set { title = value; } } private string body; /// <summary> /// 发送内容,可以包含html /// </summary> public string Body { get { return body; } set { body = value; } } private List<string> toEmail = new List<string>(); /// <summary> /// 发送给谁,可以多用户 /// </summary> public List<string> ToEmail { get { return toEmail; } set { toEmail = value; } } private string toDis; /// <summary> /// 发送给谁的描述 /// </summary> public string ToDis { get { return toDis; } set { toDis = value; } } private string fromDis; /// <summary> /// 发送人描述 /// </summary> public string FromDis { get { return fromDis; } set { fromDis = value; } } public SendEmail(string title, string body, List<string> toEmail, string toDis, string fromDis) { this.title = title; this.body = body; this.toEmail = toEmail; this.toDis = toDis; this.fromDis = fromDis; } #region 邮件发送方法 /// <summary> /// 利用线程来发送邮件,减少系统响应时间 /// </summary> public void WebEmail() { try { Thread thread = new Thread(new ThreadStart(SendWebEmail)); thread.Start(); } catch { throw; } } public void SendWebEmail() { try { foreach (string toEmailName in this.ToEmail) { MailAddress from = new MailAddress(SendConfig.EmailName, this.FromDis); //SendConfig.EmailName是发送邮件的邮箱名称 MailAddress to = new MailAddress(toEmailName, this.ToDis); MailMessage msg = new MailMessage(from, to); msg.Priority = MailPriority.High; msg.Subject = this.Title; msg.Body = this.Body; msg.BodyEncoding = System.Text.Encoding.UTF8; msg.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.Host = SendConfig.SMTP; //SendConfig.SMTP是发送邮件的邮箱的SMTP smtp.UseDefaultCredentials = false; smtp.Credentials = new System.Net.NetworkCredential(SendConfig.EmailName, SendConfig.EmailPwd); //SendConfig.EmailPwd是发送邮件的邮箱的密码 smtp.DeliveryMethod = SmtpDeliveryMethod.Network; smtp.Send(msg); } } catch (Exception e) { throw; } } #endregion
程序需要引用:
using System.Net.Mail;
using System.Threading;
这两个命名空间