先引入using System.Net.Mail; /// 发送邮件 /// <summary> /// 发送邮件 /// </summary> /// <param name="tomail">收件人邮箱地址</param> private void Sendmail(string tomail) { var smtpClient = new SmtpClient(); var mailMessage = new MailMessage(); smtpClient.Host = ConfigurationManager.AppSettings["MailHost"];//指定发送邮件的服务器地址或IP,如smtp.163.com var mailname = ConfigurationManager.AppSettings["MailName"];//发件人邮箱用户名 var mailpsd = ConfigurationManager.AppSettings["MailPassWord"];//发件人邮箱密码 smtpClient.Port = 25;//指定发送邮件端口 smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = new System.Net.NetworkCredential(mailname, mailpsd); smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; mailMessage.BodyEncoding = Encoding.UTF8; mailMessage.IsBodyHtml = true;//是否为html格式 mailMessage.Priority = MailPriority.High;//发送邮件的优先等级 mailMessage.From = new MailAddress(mailname); mailMessage.To.Add(tomail); mailMessage.Subject = "发送邮件测试";//邮件主题 string[] file = {"c:\\log.7z","c:\\log.rar"}; mailMessage.Attachments.Clear(); //添加邮件附件,可发送多个文件 foreach (var filename in file) { mailMessage.Attachments.Add(new Attachment(filename, MediaTypeNames.Application.Octet)); } mailMessage.Body = GetBody();//邮件内容 try { smtpClient.Send(mailMessage); } catch (SmtpException ex) { throw new Exception("邮箱异常!" + ex.Message); } } /// 邮件内容格式 /// <summary> /// 邮件内容格式 /// </summary> private static string GetBody() { var htmlBody = new StringBuilder(); htmlBody.Append("<body style=\"font-size:10pt\">"); htmlBody.Append("<div style=\"font-size:10pt; font-weight:bold\">尊敬的用户您好:</div>"); htmlBody.Append("<br/>"); htmlBody.Append("<div> 欢迎注册成为【xx】的会员</div>"); htmlBody.Append("<br/><br/><br/>"); htmlBody.Append("<div style=\"text-align:right\">" + DateTime.Now.Year + "年" + DateTime.Now.Month + "月" + DateTime.Now.Day + "日</div></body>"); return htmlBody.ToString(); }