1. 程式人生 > 程式設計 >c# 實現傳送郵件的功能

c# 實現傳送郵件的功能

微軟已經為我們準備好了現成的工具類供我們呼叫:

MailMessage//郵件資訊類
SmtpClient//郵件傳送類

首先需要在專案的類檔案中引用以下名稱空間:

using System.Net;
using System.Net.Mail;

然後直接上封裝好的程式碼:

/// <summary>
/// 傳送郵件方法
/// </summary>
/// <param name="mailTo">接收人郵件</param>
/// <param name="mailTitle">傳送郵件標題</param>
/// <param name="mailContent">傳送郵件內容</param>
/// <returns></returns>
public static bool SendEmail(string mailTo,string mailTitle,string mailContent)
{
  //設定傳送方郵件資訊,例如:qq郵箱
  string stmpServer = @"smtp.qq.com";//smtp伺服器地址
  string mailAccount = @"[email protected]";//郵箱賬號
  string pwd = @"xcryxiqzzasaebbe";//郵箱密碼(qq郵箱此處使用授權碼,其他郵箱見郵箱規定使用的是郵箱密碼還是授權碼)

  //郵件服務設定
  SmtpClient smtpClient = new SmtpClient();
  smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定電子郵件傳送方式
  smtpClient.Host = stmpServer;//指定傳送方SMTP伺服器
  smtpClient.EnableSsl = true;//使用安全加密連線
  smtpClient.UseDefaultCredentials = true;//不和請求一起傳送
  smtpClient.Credentials = new NetworkCredential(mailAccount,pwd);//設定傳送賬號密碼

  MailMessage mailMessage = new MailMessage(mailAccount,mailTo);//例項化郵件資訊實體並設定傳送方和接收方
  mailMessage.Subject = mailTitle;//設定傳送郵件得標題
  mailMessage.Body = mailContent;//設定傳送郵件內容
  mailMessage.BodyEncoding = Encoding.UTF8;//設定傳送郵件得編碼
  mailMessage.IsBodyHtml = false;//設定標題是否為HTML格式
  mailMessage.Priority = MailPriority.Normal;//設定郵件傳送優先順序

  try
  {
    smtpClient.Send(mailMessage);//傳送郵件
    return true;
  }
  catch (SmtpException ex)
  {
    throw ex;
  }
}

常見問題及錯誤彙總:

1.郵箱授權碼怎麼獲取,以qq郵箱為例:

c# 實現傳送郵件的功能

c# 實現傳送郵件的功能

2.丟擲錯誤:System.Net.Mail.SmtpException:“命令順序不正確。 伺服器響應為:Error: need EHLO and AUTH first !”

c# 實現傳送郵件的功能

​解決方案:確認郵箱是使用密碼直接登入,還是授權碼;

3.丟擲錯誤:mail from address must be same as authorization user

​一般是郵箱賬戶設定中的 POP3/IMAP/SMTP 未開啟

以qq郵箱為例:同樣在賬戶設定中找到下圖,開啟紅框中的選項即可。

c# 實現傳送郵件的功能

以上就是c# 實現傳送郵件的功能的詳細內容,更多關於c# 傳送郵件的資料請關注我們其它相關文章!