C#SMTP發郵件
簡單郵件傳輸協議 (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 = "[email protected]";// 發送端賬號
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 = "[email protected]";
string strcc = "[email protected]";//抄送
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 的發送者要保持一致。
紅包+折扣,阿里雲上雲大禮包!
https://promotion.aliyun.com/ntms/yunparter/invite.html?userCode=5wzgtzow
【全民雲計算】 雲主機低至4折
https://promotion.aliyun.com/ntms/act/qwbk.html?userCode=5wzgtzow
【阿里雲新用戶】 雲通信專享8折
https://www.aliyun.com/acts/alicomcloud/new-discount?userCode=5wzgtzow
【商標註冊服務】 低至680
https://tm.aliyun.com/?userCode=5wzgtzow