C# 发送电子邮件
软件开发技术交流,同学习共进步,欢迎加群, 群号:169600532
首先,web.config设置邮件服务器配置
1 <system.net> 2 <mailSettings> 3 <smtp from="" deliveryMethod="Network"> 4 <network host="" port="25" userName="" password="" targetName=""/> 5 </smtp> 6 </mailSettings> 7 </system.net>
当然,其中空白的值,需要根据各自的情况填写
获取配置的代码:
SmtpSection smtpCfg = NetSectionGroup.GetSectionGroup(WebConfigurationManager.OpenWebConfiguration("~/web.config")).MailSettings.Smtp;
接下来创建MailMessage对象,并设置属性
1 System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); 2 msg.From = new System.Net.Mail.MailAddress(smtpCfg.From, smtpCfg.Network.TargetName, System.Text.Encoding.UTF8); 3 //msg.To.Add("收件人地址"); 4 string[] temp = to.Trim(',').Split(','); 5 foreach (var item in temp) 6 { 7 msg.To.Add(item + "@XX.com.cn"); 8 } 9 //msg.CC.Add("抄送人地址"); 10 if (!string.IsNullOrEmpty(cc)) 11 { 12 temp = cc.Trim(',').Split(','); 13 foreach (var item in temp) 14 { 15 msg.CC.Add(item + "@XX.com.cn"); 16 } 17 } 18 msg.Subject = title; 19 msg.Body = body; 20 msg.BodyEncoding = System.Text.Encoding.UTF8;//正文编码 21 msg.IsBodyHtml = true; 22 msg.Priority = System.Net.Mail.MailPriority.High;//优先级
完整代码:
此处收件人,抄送人默认是统一的邮箱后缀,默认收件人,抄送人传的只是邮件名,非完整邮箱地址;当然你也可以改进,直接收件人,抄送人是完整邮箱地址
1 /// <summary> 2 /// 发送邮件 3 /// </summary> 4 /// <param name="to">收件人【多个以','分隔】</param> 5 /// <param name="title">标题</param> 6 /// <param name="body">邮件正文</param> 7 /// <param name="cc">抄送人【多个以','分隔】</param> 8 private void SendMail(string to, string title, string body, string cc="") 9 { 10 SmtpSection smtpCfg = NetSectionGroup.GetSectionGroup(WebConfigurationManager.OpenWebConfiguration("~/web.config")).MailSettings.Smtp; 11 12 System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); 13 msg.From = new System.Net.Mail.MailAddress(smtpCfg.From, smtpCfg.Network.TargetName, System.Text.Encoding.UTF8); 14 //msg.To.Add("收件人地址"); 15 string[] temp = to.Trim(',').Split(','); 16 foreach (var item in temp) 17 { 18 msg.To.Add(item + "@XX.com.cn"); 19 } 20 //msg.CC.Add("抄送人地址"); 21 if (!string.IsNullOrEmpty(cc)) 22 { 23 temp = cc.Trim(',').Split(','); 24 foreach (var item in temp) 25 { 26 msg.CC.Add(item + "@XX.com.cn"); 27 } 28 } 29 msg.Subject = title; 30 msg.Body = body; 31 msg.BodyEncoding = System.Text.Encoding.UTF8;//正文编码 32 msg.IsBodyHtml = true; 33 msg.Priority = System.Net.Mail.MailPriority.High;//优先级 34 35 36 System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(smtpCfg.Network.Host,smtpCfg.Network.Port); 37 38 smtp.Credentials = new System.Net.NetworkCredential(smtpCfg.Network.UserName, smtpCfg.Network.Password); 39 try 40 { 41 //smtp.SendAsync(msg, ""); 42 //smtp.SendMailAsync("发件人地址","收件人地址","邮件主题","邮件正文"); 43 smtp.SendMailAsync(msg); 44 } 45 catch (Exception e) 46 { 47 smtp.Send(msg); 48 //throw new Exception(e.ToString()); 49 } 50 }
在此抛砖,谢谢大家!
软件开发技术交流,同学习共进步,欢迎加群, 群号:169600532