C#基于System.Net.Mail实现SMTP邮件发送服务类
在网站应用开发中,邮件发送是一项常见需求,例如用户在博客评论区留言后,系统自动向管理员邮箱发送通知。本文将整理并展示一个客户端Demo示例,旨在为有相关需求的开发者提供参考。运行效果见下图:

核心实现代码如下:
复制代码 代码如下:using System; using System.Net; using System.Net.Mail; using System.Text; namespace HC.Email { /// /// 整站邮件服务类 /// public class EmailService { /// /// 发送邮件 /// /// 收件人 /// 主题 /// 内容 /// public static bool Send(string mailTo, string subject, string body) { return Send(new[] {mailTo}, null, subject, body, true, null); } /// /// 发送邮件 /// /// 收件人 /// 主题 /// 内容 /// public static bool Send(string[] mailTo, string subject, string body) { return Send(mailTo, null, subject, body, true, null); } /// /// 发送邮件 /// /// 收件人 /// 主题 /// 内容 /// 附件 /// public static bool Send(string[] mailTo, string subject, string body, string[] attachmentsPath) { return Send(mailTo, null, subject, body, true, attachmentsPath); } /// /// 发送邮件 /// /// 收件人 /// 抄送 /// 主题 /// 内容 /// 是否Html /// 附件 /// public static bool Send(string[] mailTo, string[] mailCcArray, string subject,string body, bool isBodyHtml, string[] attachmentsPath) { try { var config = ConfigHelper.GetConfig(); if (string.IsNullOrEmpty(config.Host) ||string.IsNullOrEmpty(config.UserName) || string.IsNullOrEmpty(config.Port) ||string.IsNullOrEmpty(config.Password)) { //todo:记录日志 return false; } var @from = new MailAddress(config.MailFrom); //使用指定的邮件地址初始化MailAddress实例 var message = new MailMessage(); //初始化MailMessage实例 //向收件人地址集合添加邮件地址 if (mailTo != null) { foreach (string t in mailTo) { message.To.Add(t); } } //向抄送收件人地址集合添加邮件地址 if (mailCcArray != null) { foreach (string t in mailCcArray) { message.CC.Add(t); } } //发件人地址 message.From = @from; //电子邮件的标题 message.Subject = subject; //电子邮件的主题内容使用的编码 message.SubjectEncoding = Encoding.UTF8; //电子邮件正文 message.Body = body; //电子邮件正文的编码 message.BodyEncoding = Encoding.Default; message.Priority = MailPriority.High; message.IsBodyHtml = isBodyHtml; //在有附件的情况下添加附件 if (attachmentsPath != null && attachmentsPath.Length > 0) { foreach (string path in attachmentsPath) { var attachFile = new Attachment(path); message.Attachments.Add(attachFile); } } try { var smtp = new SmtpClient { Credentials = new NetworkCredential(config.UserName, config.Password), Host = config.Host, Port = Convert.ToInt32(config.Port) }; //将邮件发送到SMTP邮件服务器 smtp.Send(message); //todo:记录日志 return true; } catch (SmtpException ex) { //todo:记录日志 return false; } } catch (SmtpException ex) { //todo:记录日志 return false; } } } }
完整实例代码点击此处本站下载。
希望本文所述对大家的C#程序设计有所帮助