C# 使用系统方法发送异步邮件
最近在对几年前的一个项目进行重构,发现发送邮件功能需要一定的时间来处理,而由于发送是同步的因此导致在发送邮件时无法执行后续的操作
/****************************************************************** * 创建人: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.baidu.com"; private readonly string UserName = "support@baidu.com"; readonly string Pwd = "baidu.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#发送邮件时提示:“不允许使用邮箱名称。服务器响应为:”的错误解决办法
由于项目需要,要为客户提供一个定期发送邮件的程序。本来原来自己还写过,但新写的程序一晚上也没通过测试,总是提示"不允许使用邮箱名称。服务器响应为..."
经过在网上搜索查找解决办法,似乎解决办法都是一个,就是把smtp.UseDefaultCredentials = true;写到smtp.Credentials = new NetworkCredential("myusername", "mypwd");的前面。
但使用此方法,也未能解决问题。
后来,我从邮箱设置入手,发现现在大多邮箱都采用了设置smtp发邮件和客户端授权码的双重功能,以126为例,在126邮箱网页版的设置里,就能看到,如下图
后期,我将smtp.Credentials = new NetworkCredential("myusername", "mypwd")中的mypwd换成了我的客户端授权码,立即通过了测试。
希望朋友们碰到此种问题也多一种解决办法。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)