前言
本篇主要记录:VS2019 WinFrm桌面应用程序通过SMTP方式实现邮件发送。作为Delphi转C#的关键一步,接下来将逐步实现Delphi中常用到的功能。
准备工作
搭建WinFrm前台界面
添加必要的控件,这里主要应用到GroupBox、Label、TextBox和Button,如下图
发件邮箱账户配置
准备一个邮箱,开启SMTP服务,并开启客户端授权密码(此处需要注意)。
核心代码构造SendEMail类
代码如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Net.Mail; 5 using System.Text; 6 using System.Threading.Tasks; 7 8 namespace SendMail 9 { 10 /// <summary> 11 /// SMTP方式发送邮件 12 /// 特别注意:这里的密码为客户端授权码,不是发送邮箱的密码 13 /// </summary> 14 class SendEMail 15 { 16 /// <summary> 17 /// 发送邮件 18 /// </summary> 19 /// <param name="userEmailAddress">发件人地址</param> 20 /// <param name="userName">发件人姓名(可为空)</param> 21 /// <param name="password">密码</param> 22 /// <param name="host">邮件服务器地址</param> 23 /// <param name="port"></param> 24 /// <param name="sendToList">收件人(多个电子邮件地址之间必须用逗号字符(“,”)分隔)</param> 25 /// <param name="sendCCList">抄送人(多个电子邮件地址之间必须用逗号字符(“,”)分隔)</param> 26 /// <param name="subject">主题</param> 27 /// <param name="body">内容</param> 28 /// <param name="attachmentsPath">附件路径</param> 29 /// <param name="errorMessage">错误信息</param> 30 public static bool SendMessage(string userEmailAddress, string userName, string password, string host, int port, 31 string[] sendToList, string[] sendCCList, string subject, string body, string[] attachmentsPath, out string errorMessage) 32 { 33 errorMessage = string.Empty; 34 SmtpClient client = new SmtpClient(); 35 client.UseDefaultCredentials = true; 36 client.Credentials = new System.Net.NetworkCredential(userEmailAddress, password);//用户名、客户端授权码*******特别注意:此处需要的是客户端授权码,不是邮箱密码******* 37 client.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式 38 client.Host = host;//邮件服务器 39 client.Port = port;//端口号 非SSL方式,默认端口号为:25 40 MailMessage msg = new MailMessage(); 41 //加发件人 42 foreach (string send in sendToList) 43 { 44 msg.To.Add(send); 45 } 46 //加抄送 47 foreach (string cc in sendCCList) 48 { 49 msg.CC.Add(cc); 50 } 51 //在有附件的情况下添加附件 52 if (attachmentsPath != null && attachmentsPath.Length > 0) 53 { 54 foreach (string path in attachmentsPath) 55 { 56 var attachFile = new Attachment(path); 57 msg.Attachments.Add(attachFile); 58 } 59 } 60 msg.From = new MailAddress(userEmailAddress, userName);//发件人地址 61 msg.Subject = subject;//邮件标题 62 msg.Body = body;//邮件内容 63 msg.BodyEncoding = System.Text.Encoding.UTF8;//邮件内容编码 64 msg.IsBodyHtml = true;//是否是HTML邮件 65 msg.Priority = MailPriority.High;//邮件优先级 66 try 67 { 68 client.Send(msg); 69 return true; 70 } 71 catch (System.Net.Mail.SmtpException ex) 72 { 73 errorMessage = ex.Message; 74 return false; 75 } 76 } 77 } 78 }
实现效果
作者:Jeremy.Wu
出处:https://www.cnblogs.com/jeremywucnblog/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。