C#使用QQ、163邮箱发送邮件(新手易懂)
前提准备:以QQ邮件为例,前往QQ个人邮箱开启POP3/SMTP服务(腾讯默认关闭状态),开启后获得授权码,并复制保存好。(使用第三方发送邮件,不必填写QQ密码,而是使用授权码)
POP3/SMTP服务开启流程:依次点击设置—账户—往下滑动可看到该服务
需要引用:
using System.Net.Mail;
using System.Net.Mime;
1 public class myEmailHelper 2 { 3 /// <summary> 4 /// SMTP实例 5 /// </summary> 6 static System.Net.Mail.SmtpClient client = null; 7 8 /// <summary> 9 /// 发送信息 10 /// </summary> 11 /// <param name="Receiver">邮件接收人</param> 12 /// <param name="Subject">邮件主题</param> 13 /// <param name="content">邮件内容</param> 14 public void SendEmail(string Receiver, string Subject, string content) 15 { 16 if (string.IsNullOrEmpty(Receiver) || string.IsNullOrEmpty(Subject) 17 || string.IsNullOrEmpty(content)) 18 { 19 throw new ArgumentNullException("SendEmail参数空异常!"); 20 } 21 if (client == null) 22 { 23 try 24 { 25 //163发送配置 26 //client = new System.Net.Mail.SmtpClient(); 27 //client.Host = "smtp.163.com"; 28 //client.Port = 25; 29 //client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; 30 //client.EnableSsl = true; 31 //client.UseDefaultCredentials = true; 32 33 34 //qq发送配置的参数//切EnableSsl必须设置为true 35 client = new System.Net.Mail.SmtpClient(); 36 client.Host = "smtp.qq.com"; 37 client.Port = 25; 38 client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; 39 client.EnableSsl = true; 40 client.UseDefaultCredentials = false; 41 42 client.Credentials = new System.Net.NetworkCredential("你的邮箱", "授权码"); 43 } 44 catch (Exception ex) 45 { 46 throw ex; 47 } 48 } 49 try 50 { 51 System.Net.Mail.MailMessage Message = new System.Net.Mail.MailMessage(); 52 Message.SubjectEncoding = System.Text.Encoding.UTF8; 53 Message.BodyEncoding = System.Text.Encoding.UTF8; 54 Message.Priority = System.Net.Mail.MailPriority.High; 55 56 Message.From = new System.Net.Mail.MailAddress("你的邮箱", "发送显示名"); 57 //添加邮件接收人地址 58 string[] receivers = Receiver.Split(new char[] { \',\' }); 59 Array.ForEach(receivers.ToArray(), ToMail => { Message.To.Add(ToMail); }); 60 61 Message.Subject = Subject; 62 Message.Body = content; 63 Message.IsBodyHtml = true; 64 client.Send(Message); 65 } 66 catch (Exception ex) 67 { 68 throw ex; 69 } 70 } 71 }
Tips:授权码获得之后一定要先复制好,不然下一次获取需要重新生成,避免多余操作。授权码不区分大小写
版权声明:本文为ylblogss原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。