//============================================================
// 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);;
}
商業源碼熱門下載www.html.org.cn
新聞熱點
疑難解答