簡單郵件傳輸協議 (Simple Mail Transfer Protocol, SMTP) 是事實上的在Internet傳輸email的標准。
C#郵件傳輸主要用到了
SmtpClient 和MailMessage 類。
SmtpClient類是客戶端類,客戶端的Send方法實現了發送郵件的功能。Send方法的參數是MailMessage對象。
MailMessage類是郵件信息類,通過From屬性可以設置發送者。To屬性設置接受者。CC抄送者。
Subject 標題;Body、內容。
public static void SendMailUse() { string host = "smtp.163.com";// 郵件服務器smtp.163.com表示網易郵箱服務器 string userName = "15764226619@163.com";// 發送端賬號 string password = "password";// 發送端密碼(這個客戶端重置后的密碼) SmtpClient client = new SmtpClient(); client.DeliveryMethod = SmtpDeliveryMethod.Network;//指定電子郵件發送方式 client.Host = host;//郵件服務器 client.UseDefaultCredentials = true; client.Credentials = new System.Net.NetworkCredential(userName, password);//用戶名、密碼 ////////////////////////////////////// string strfrom = userName; string strto = "1097352786@qq.com"; string strcc = "2605625733@qq.com";//抄送 string subject = "這是測試郵件標題5";//郵件的主題 string body = "測試郵件內容5";//發送的郵件正文 System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage(); msg.From=new MailAddress(strfrom,"xyf"); msg.To.Add(strto); msg.CC.Add(strcc); msg.Subject = subject;//郵件標題 msg.Body = body;//郵件內容 msg.BodyEncoding = System.Text.Encoding.UTF8;//郵件內容編碼 msg.IsBodyHtml = true;//是否是HTML郵件 msg.Priority = MailPriority.High;//郵件優先級 try { client.Send(msg); Console.WriteLine("發送成功"); } catch (System.Net.Mail.SmtpException ex) { Console.WriteLine(ex.Message, "發送郵件出錯"); } }
以上代碼注意,將密碼改為自己的密碼。
注意
SmtpClient 的用戶名和
MailMessage 的發送者要保持一致。