使用 SmtpClient发送电子邮件
SmtpClient不支持许多现代协议。这对于从工具发送一封电子邮件非常有用,但不能适应该协议的现代要求。 官方建议新开发改为使用 MailKit 或其他库。
/// <summary> /// 发送带附件的邮件 /// </summary> /// <param name="to">收件人</param> /// <param name="subject">邮件主题</param> /// <param name="mailBody">邮件内容</param> /// <param name="sendFiles">要做为附件发送的文件列表</param> public static void SendMail(string to, string subject, string mailBody, List<string> sendFiles, MailPriority mailPriority = MailPriority.Normal) { try { SmtpClient smtp = new SmtpClient(); smtp.Host = "smtp.exmail.qq.com";//SMTP主机 smtp.Credentials = new System.Net.NetworkCredential("username", "password"); smtp.Port = 25; //电子邮件信息类 MailAddress fromAddress = new MailAddress("test@qq.com");//发件人Email //MailAddress toAddress = new MailAddress(to);//收件人Email MailMessage mailMessage = new MailMessage();//创建一个电子邮件类 mailMessage.From = fromAddress; mailMessage.To.Clear(); foreach (string mailAddr in to.Split(",".ToCharArray())) { //收件人Email mailMessage.To.Add(new MailAddress(mailAddr)); } mailMessage.Subject = subject; mailMessage.Body = mailBody;//可为html格式文本 mailMessage.SubjectEncoding = System.Text.Encoding.UTF8;//邮件主题编码 mailMessage.BodyEncoding = System.Text.Encoding.GetEncoding("GB2312");//邮件内容编码 mailMessage.IsBodyHtml = true;//邮件内容是否为html格式 mailMessage.Priority = mailPriority;//邮件的优先级,有三个值:高(在邮件主题前有一个红色感叹号,表示紧急),低(在邮件主题前有一个蓝色向下箭头,表示缓慢),正常(无显示). if (sendFiles == null) { sendFiles = new List<string>(); } if (sendFiles.Count > 0) { //添加附件 foreach (string filename in sendFiles) { if (System.IO.File.Exists(filename)) { mailMessage.Attachments.Add(new Attachment(filename)); } } } smtp.Send(mailMessage); } catch (Exception ex) { } }