前提准備:以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:授權碼獲得之后一定要先復制好,不然下一次獲取需要重新生成,避免多余操作。授權碼不區分大小寫