欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > asp.net >内容正文

asp.net

利用System.Net.Mail和多线程实现邮件发送

发布时间:2025/4/5 asp.net 61 豆豆
生活随笔 收集整理的这篇文章主要介绍了 利用System.Net.Mail和多线程实现邮件发送 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

对于邮件发送,一般来说,程序会响应超过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是发送邮件的邮箱的SMTPsmtp.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 View Code

程序需要引用:

using System.Net.Mail;
using System.Threading;

这两个命名空间

转载于:https://www.cnblogs.com/chusdd/p/3611961.html

总结

以上是生活随笔为你收集整理的利用System.Net.Mail和多线程实现邮件发送的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。