程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> C#-MailSender郵件發送組件源代碼(支持ESMTP, 附件)

C#-MailSender郵件發送組件源代碼(支持ESMTP, 附件)

編輯:關於C語言

//============================================================
// File: MailSender.cs
// 郵件發送組件
// 支持ESMTP, 多附件
//============================================================

namespace JcPersonal.Utility
{
using System;;
using System.Collections;;
using System.Net.Sockets;;
using System.IO;;
using System.Text;;

/// 〈summary〉
/// Mail 發送器
/// 〈/summary〉
public class MailSender
{

  /// 〈summary〉

  /// SMTP服務器域名

  /// 〈/summary〉

  public string Server {

   get { return server;; }

   set { if (value != server) server = value;; }

  } private string server = "";;


  /// 〈summary〉

  /// SMTP服務器端口 [默認為25]

  /// 〈/summary〉

  public int Port {

   get { return port;; }

   set { if (value != port) port = value;; }

  } private int port = 25;;


  /// 〈summary〉

  /// 用戶名 [如果需要身份驗證的話]

  /// 〈/summary〉

  public string UserName {

   get { return userName;; }

   set { if (value != userName) userName = value;; }

  } private string userName = "";;


  /// 〈summary〉

  /// 密碼 [如果需要身份驗證的話]

  /// 〈/summary〉

  public string PassWord {

   get { return passWord;; }

   set { if (value != password) passWord = value;; }

  } private string passWord = "";;


  /// 〈summary〉

  /// 發件人地址

  /// 〈/summary〉

  public string From {

   get { return from;; }

   set { if (value != from) from = value;;}

  } private string from = "";;


  /// 〈summary〉

  /// 收件人地址

  /// 〈/summary〉

  public string To {

   get { return to;; }

   set { if (value != to) to = value;;}

  } private string to = "";;


  /// 〈summary〉

  /// 發件人姓名

  /// 〈/summary〉

  public string FromName {

   get { return fromName;; }

   set { if (value != fromName) fromName = value;; }

  } private string fromName = "";;


  /// 〈summary〉

  /// 收件人姓名

  /// 〈/summary〉

  public string ToName {

   get { return toName;; }

   set { if (value != toName) toName = value;; }

  } private string toName = "";;


  /// 〈summary〉

  /// 郵件的主題

  /// 〈/summary〉

  public string Subject {

   get { return subject;; }

   set { if (value != subject) subject = value;; }

  } private string subject = "";;


  /// 〈summary〉

  /// 郵件正文

  /// 〈/summary〉

  public string Body {

   get { return body;; }

   set { if (value != body) body = value;; }

  } private string body = "";;


  /// 〈summary〉

  /// 超文本格式的郵件正文

  /// 〈/summary〉

  public string HtmlBody {

   get { return HtmlBody;; }

   set { if (value != htmlBody) HtmlBody = value;; }

  } private string HtmlBody = "";;


  /// 〈summary〉

  /// 是否是Html格式的郵件

  /// 〈/summary〉

  public bool IsHtml {

   get { return isHtml;; }

   set { if (value != isHtml) isHtml = value;; }

  } private bool isHtml = false;;


  /// 〈summary〉

  /// 語言編碼 [默認為GB2312]

  /// 〈/summary〉

  public string LanguageEncoding {

   get { return languageEncoding;; }

   set { if (value != languageEncoding) languageEncoding = value;; }

  } private string languageEncoding = "GB2312";;


  /// 〈summary〉

  /// 郵件編碼 [默認為8bit]

  /// 〈/summary〉

  public string MailEncoding {

   get { return encoding;; }

   set { if (value != encoding) encoding = value;; }

  } private string encoding = "8bit";;


  /// 〈summary〉

  /// 郵件優先級 [默認為3]

  /// 〈/summary〉

  public int Priority {

   get { return priority;; }

   set { if (value != priority) priority = value;; }

  } private int priority = 3;;


  /// 〈summary〉

  /// 附件 [AttachmentInfo]

  /// 〈/summary〉

  public IList Attachments {

   get { return attachments;; }
// set { if (value != attachments) attachments = value;; }

  } private ArrayList attachments = new ArrayList ();;

  /// 〈summary〉

  /// 發送郵件

  /// 〈/summary〉

  public void SendMail ()

  {

   // 創建TcpClIEnt對象, 並建立連接

   TcpClIEnt tcp = null;;

   try

   {

   tcp = new TcpClIEnt (server, port);;

   }

   catch (Exception)

   {

   throw new Exception ("無法連接服務器");;

   }


   ReadString (tcp.GetStream());;//獲取連接信息


   // 開始進行服務器認證

   // 如果狀態碼是250則表示操作成功

   if (!Command (tcp.GetStream(), "EHLO Localhost", "250"))

   throw new Exception ("登陸階段失敗");;


   if (userName != "")

   {

   // 需要身份驗證

   if (!Command (tcp.GetStream(), "AUTH LOGIN", "334"))

   throw new Exception ("身份驗證階段失敗");;

   string nameB64 = ToBase64 (userName);; // 此處將username轉換為Base64碼

   if (!Command (tcp.GetStream(), nameB64, "334"))

   throw new Exception ("身份驗證階段失敗");;

   string passB64 = ToBase64 (password);; // 此處將passWord轉換為Base64碼

   if (!Command (tcp.GetStream(), passB64, "235"))

   throw new Exception ("身份驗證階段失敗");;

   }

   // 准備發送

   WriteString (tcp.GetStream(), "mail From: " + from);;

   WriteString (tcp.GetStream(), "rcpt to: " + to);;

   WriteString (tcp.GetStream(), "data");;


   // 發送郵件頭

   WriteString (tcp.GetStream(), "Date: " + DateTime.Now);; // 時間

   WriteString (tcp.GetStream(), "From: " + fromName + "〈" + from + "〉");; // 發件人

   WriteString (tcp.GetStream(), "Subject: " + subject);; // 主題

   WriteString (tcp.GetStream(), "To:" + toName + "〈" + to + "〉");; // 收件人


   //郵件格式

   WriteString (tcp.GetStream(), "Content-Type: multipart/mixed;; boundary=\"unique-boundary-1\"");;

   WriteString (tcp.GetStream(), "Reply-To:" + from);; // 回復地址

   WriteString (tcp.GetStream(), "X-Priority:" + priority);; // 優先級

   WriteString (tcp.GetStream(), "MIME-Version:1.0");; // MIME版本


   // 數據ID,隨意
// WriteString (tcp.GetStream(), "Message-Id: " + DateTime.Now.ToFileTime() + "@security.com");;

   WriteString (tcp.GetStream(), "Content-Transfer-Encoding:" + encoding);; // 內容編碼

   WriteString (tcp.GetStream(), "X-Mailer:JcPersonal.Utility.MailSender");; // 郵件發送者

   WriteString (tcp.GetStream(), "");;


   WriteString (tcp.GetStream(), ToBase64 ("This is a multi-part message in MIME format."));;

   WriteString (tcp.GetStream(), "");;


   // 從此處開始進行分隔輸入

   WriteString (tcp.GetStream(), "--unique-boundary-1");;


   // 在此處定義第二個分隔符

   WriteString (tcp.GetStream(), "Content-Type: multipart/alternative;;Boundary=\"unique-boundary-2\"");;

   WriteString (tcp.GetStream(), "");;


   if(!isHtml)

   {

   // 文本信息

   WriteString (tcp.GetStream(), "--unique-boundary-2");;

   WriteString (tcp.GetStream(), "Content-Type: text/plain;;charset=" + languageEncoding);;

   WriteString (tcp.GetStream(), "Content-Transfer-Encoding:" + encoding);;

   WriteString (tcp.GetStream(), "");;

   WriteString (tcp.GetStream(), body);;

   WriteString (tcp.GetStream(), "");;//一個部分寫完之後就寫如空信息,分段

   WriteString (tcp.GetStream(), "--unique-boundary-2--");;//分隔符的結束符號,尾巴後面多了--

   WriteString (tcp.GetStream(), "");;

   }

   else

   {

   //Html信息

   WriteString (tcp.GetStream(), "--unique-boundary-2");;

   WriteString (tcp.GetStream(), "Content-Type: text/Html;;charset=" + languageEncoding);;

   WriteString (tcp.GetStream(), "Content-Transfer-Encoding:" + encoding);;

   WriteString (tcp.GetStream(), "");;

   WriteString (tcp.GetStream(), HtmlBody);;

   WriteString (tcp.GetStream(), "");;

   WriteString (tcp.GetStream(), "--unique-boundary-2--");;//分隔符的結束符號,尾巴後面多了--

   WriteString (tcp.GetStream(), "");;

   }


   // 發送附件

   // 對文件列表做循環

   for (int i = 0;; i 〈 attachments.Count;; i++)

   {

   WriteString (tcp.GetStream(), "--unique-boundary-1");; // 郵件內容分隔符

   WriteString (tcp.GetStream(), "Content-Type: application/octet-stream;;name=\"" + ((AttachmentInfo)attachments[i]).FileName + "\"");; // 文件格式

   WriteString (tcp.GetStream(), "Content-Transfer-Encoding: base64");; // 內容的編碼

   WriteString (tcp.GetStream(), "Content-Disposition:attachment;;filename=\"" + ((AttachmentInfo)attachments[i]).FileName + "\"");; // 文件名

   WriteString (tcp.GetStream(), "");;

   WriteString (tcp.GetStream(), ((AttachmentInfo)attachments[i]).Bytes);; // 寫入文件的內容

   WriteString (tcp.GetStream(), "");;

   }


   Command (tcp.GetStream(), ".", "250");; // 最後寫完了,輸入"."


   // 關閉連接

   tcp.Close ();;

  }


  /// 〈summary〉

  /// 向流中寫入字符

  /// 〈/summary〉

  /// 〈param name="netStream"〉來自TcpClIEnt的流〈/param〉

  /// 〈param name="str"〉寫入的字符〈/param〉

  protected void WriteString (NetworkStream netStream, string str)

  {

   str = str + "\r\n";; // 加入換行符


   // 將命令行轉化為byte[]

   byte[] bWrite = Encoding.GetEncoding(languageEncoding).GetBytes(str.ToCharArray());;


   // 由於每次寫入的數據大小是有限制的,那麼我們將每次寫入的數據長度定在75個字節,一旦命令長度超過了75,就分步寫入。

   int start=0;;

   int length=bWrite.Length;;

   int page=0;;

   int size=75;;

   int count=size;;

   try

   {

   if (length〉75)

   {

   // 數據分頁

   if ((length/size)*size〈length)

   page=length/size+1;;

   else

   page=length/size;;

   for (int i=0;;i〈page;;i++)

   {

   start=i*size;;

   if (i==page-1)

   count=length-(i*size);;

   netStream.Write(bWrite,start,count);;// 將數據寫入到服務器上

   }

   }

   else

   netStream.Write(bWrite,0,bWrite.Length);;

   }

   catch(Exception)

   {

   // 忽略錯誤

   }

  }


  /// 〈summary〉

  /// 從流中讀取字符

  /// 〈/summary〉

  /// 〈param name="netStream"〉來自TcpClIEnt的流〈/param〉

  /// 〈returns〉讀取的字符〈/returns〉

  protected string ReadString (NetworkStream netStream)

  {

   string sp = null;;

   byte[] by = new byte[1024];;

   int size = netStream.Read(by,0,by.Length);;// 讀取數據流

   if (size 〉 0)

   {

   sp = Encoding.Default.GetString(by);;// 轉化為String

   }

   return sp;;

  }


  /// 〈summary〉

  /// 發出命令並判斷返回信息是否正確

  /// 〈/summary〉

  /// 〈param name="netStream"〉來自TcpClIEnt的流〈/param〉

  /// 〈param name="command"〉命令〈/param〉

  /// 〈param name="state"〉正確的狀態碼〈/param〉

  /// 〈returns〉是否正確〈/returns〉

  protected bool Command (NetworkStream netStream, string command, string state)

  {

   string sp=null;;

   bool success=false;;

   try

   {

   WriteString (netStream, command);;// 寫入命令

   sp = ReadString (netStream);;// 接受返回信息

   if (sp.IndexOf(state) != -1)// 判斷狀態碼是否正確

   success=true;;

   }

   catch(Exception)

   {

   // 忽略錯誤

   }

   return success;;

  }


  /// 〈summary〉

  /// 字符串編碼為Base64

  /// 〈/summary〉

  /// 〈param name="str"〉字符串〈/param〉

  /// 〈returns〉Base64編碼的字符串〈/returns〉

  protected string ToBase64 (string str)

  {

   try

   {

   byte[] by = Encoding.Default.GetBytes (str.ToCharArray());;

   str = Convert.ToBase64String (by);;

   }

   catch(Exception)

   {

   // 忽略錯誤

   }

   return str;;

  }


  /// 〈summary〉

  /// 附件信息

  /// 〈/summary〉

  public struct AttachmentInfo

  {

   /// 〈summary〉

   /// 附件的文件名 [如果輸入路徑,則自動轉換為文件名]

   /// 〈/summary〉

   public string FileName {

   get { return fileName;; }

   set { fileName = Path.GetFileName(value);; }

   } private string fileName;;


   /// 〈summary〉

   /// 附件的內容 [由經Base64編碼的字節組成]

   /// 〈/summary〉

   public string Bytes {

   get { return bytes;; }

   set { if (value != bytes) bytes = value;; }

   } private string bytes;;


   /// 〈summary〉

   /// 從流中讀取附件內容並構造

   /// 〈/summary〉

   /// 〈param name="ifileName"〉附件的文件名〈/param〉

   /// 〈param name="stream"〉流〈/param〉

   public AttachmentInfo (string ifileName, Stream stream)

   {

   fileName = Path.GetFileName (ifileName);;

   byte[] by = new byte [stream.Length];;

   stream.Read (by,0,(int)stream.Length);; // 讀取文件內容

   //格式轉換

   bytes = Convert.ToBase64String (by);; // 轉化為base64編碼

   }


   /// 〈summary〉

   /// 按照給定的字節構造附件

   /// 〈/summary〉

   /// 〈param name="ifileName"〉附件的文件名〈/param〉

   /// 〈param name="ibytes"〉附件的內容 [字節]〈/param〉

   public AttachmentInfo (string ifileName, byte[] ibytes)

   {

   fileName = Path.GetFileName (ifileName);;

   bytes = Convert.ToBase64String (ibytes);; // 轉化為base64編碼

   }


   /// 〈summary〉

   /// 從文件載入並構造

   /// 〈/summary〉

   /// 〈param name="path"〉〈/param〉

   public AttachmentInfo (string path)

   {

   fileName = Path.GetFileName (path);;

   FileStream file = new FileStream (path, FileMode.Open);;

   byte[] by = new byte [file.Length];;

   file.Read (by,0,(int)file.Length);; // 讀取文件內容

   //格式轉換

   bytes = Convert.ToBase64String (by);; // 轉化為base64編碼

   file.Close ();;

   }

  }
}
}

--------------------------------------------------------------------------------


// 使用:


  MailSender ms = new MailSender ();;

  ms.From = "[email protected]";;

  ms.To = "[email protected]";;

  ms.Subject = "Subject";;

  ms.Body = "body text";;

  ms.UserName = "########";; // 怎麼能告訴你呢

  ms.PassWord = "********";; // 怎麼能告訴你呢

  ms.Server = "smtp.tom.com";;


  ms.Attachments.Add (new MailSender.AttachmentInfo (@"D:\test.txt"));;


  Console.WriteLine ("mail sending...");;

  try

  {

   ms.SendMail ();;

   Console.WriteLine ("mail sended.");;

  }

  catch (Exception e)

  {

   Console.WriteLine (e);;

  }

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved