版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、C#基于 SMTP協(xié)議發(fā)送電子郵件本代碼示例演示了使用TcpClient和NetWorkStream基于SMTP協(xié)議發(fā)送電子郵件的全部過(guò)程,代碼在VS2010中可以直接運(yùn)行調(diào)用方式如下: ClsSendMail obj = new ClsSendMail();obj.UserName = "你的郵箱"obj.PassWord = "郵箱密碼"bool flag = obj.Send("smtp地址", "你的郵箱", "發(fā)送人姓名", "收件人", "抄送人&quo
2、t;,true, "主題", "郵件內(nèi)容");public class ClsSendMail #region 構(gòu)造函數(shù) public ClsSendMail() _listMailTo = new List<string>(); _listMailccTo = new List<string>(); _listAttachments = new List<string>(); InitSmtpCode(); public ClsSendMail(string strSmtpServer, int intPort, s
3、tring strUserName, string strPassword) this._strSmtpServer = strSmtpServer; this._intPort = intPort; this._strUserName = strUserName; this._strPassWord = strPassword; _listMailTo = new List<string>(); _listMailccTo = new List<string>(); _listAttachments = new List<string>(); InitSm
4、tpCode(); #endregion #region 成員變量 private string _strSmtpServer = "" /郵件服務(wù)器地址 private int _intPort = 25; /服務(wù)器端口 private string _strUserName = "" / SMTP認(rèn)證時(shí)使用的用戶名 private string _strPassWord = "" / SMTP認(rèn)證時(shí)使用的密碼 private string _strMailFrom = "" / 發(fā)件人地址 private st
5、ring _strMailFromName = "" / 發(fā)件人姓名 private List<string> _listMailTo; / 收件人列表 private List<string> _listMailccTo; / 抄送收件人列表 private bool _IsHtml = false; / 是否Html郵件 private string _strPriority = "Normal" / 郵件發(fā)送優(yōu)先級(jí) private string _strSubject = "" / 郵件主題 privat
6、e string _strBody = "" / 郵件正文 private List<string> _listAttachments; / 郵件附件列表 private string _strCharSet = "GB2312" / 設(shè)定語(yǔ)言代碼,默認(rèn)設(shè)定為GB2312 private TcpClient client; / TcpClient對(duì)象,用于連接服務(wù)器 private NetworkStream NetStream; / NetworkStream對(duì)象 private Hashtable hsErrCode = new Hash
7、table(); / SMTP錯(cuò)誤代碼哈希表 private Hashtable hsRigCode = new Hashtable(); / SMTP正確代碼哈希表 private string CRLF = "rn" /回車符號(hào) private string ErrMsg = "" /記錄錯(cuò)誤消息 #region MailPriority / <summary> / 郵件發(fā)送優(yōu)先級(jí)(可設(shè)置為"High","Normal","Low"或"1","3&q
8、uot;,"5") / </summary> public enum MailPriority High, Normal, Low #endregion #region SmtpServer / <summary> / 郵件服務(wù)器地址 / </summary> public string SmtpServer get return this._strSmtpServer; set this._strSmtpServer = value; #endregion #region Port / <summary> / 服務(wù)器端口 /
9、 </summary> public int Port get return this._intPort; set this._intPort = value; #endregion #region UserName / <summary> / SMTP認(rèn)證時(shí)使用的用戶名 / </summary> public string UserName get return this._strUserName; set this._strUserName = value; #endregion #region PassWord / <summary> /
10、SMTP認(rèn)證時(shí)使用的密碼 / </summary> public string PassWord get return this._strPassWord; set this._strPassWord = value; #endregion #region Priority / <summary> / 優(yōu)先級(jí) / </summary> public string Priority get return this._strPriority; set this._strPriority = value; #endregion #region CharSet /
11、<summary> / 設(shè)定語(yǔ)言代碼,默認(rèn)設(shè)定為GB2312 / </summary> public string CharSet get return this._strCharSet; set this._strCharSet = value; #endregion #endregion #region 成員函數(shù) #region InitSmtpCode 初始化SMTP服務(wù)器返回結(jié)果Hash表 / <summary> / 初始化SMTP服務(wù)器返回結(jié)果Hash表 / </summary> private void InitSmtpCode()
12、hsErrCode.Add("500", "郵箱地址錯(cuò)誤"); hsErrCode.Add("501", "參數(shù)格式錯(cuò)誤"); hsErrCode.Add("502", "命令不可實(shí)現(xiàn)"); hsErrCode.Add("503", "服務(wù)器需要SMTP驗(yàn)證"); hsErrCode.Add("504", "命令參數(shù)不可實(shí)現(xiàn)"); hsErrCode.Add("421", &q
13、uot;服務(wù)未就緒,關(guān)閉傳輸信道"); hsErrCode.Add("450", "要求的郵件操作未完成,郵箱不可用(例如,郵箱忙)"); hsErrCode.Add("550", "要求的郵件操作未完成,郵箱不可用(例如,郵箱未找到,或不可訪問(wèn))"); hsErrCode.Add("451", "放棄要求的操作;處理過(guò)程中出錯(cuò)"); hsErrCode.Add("551", "用戶非本地,請(qǐng)嘗試<forward-path>
14、"); hsErrCode.Add("452", "系統(tǒng)存儲(chǔ)不足,要求的操作未執(zhí)行"); hsErrCode.Add("552", "過(guò)量的存儲(chǔ)分配,要求的操作未執(zhí)行"); hsErrCode.Add("553", "郵箱名不可用,要求的操作未執(zhí)行(例如郵箱格式錯(cuò)誤)"); hsErrCode.Add("432", "需要一個(gè)密碼轉(zhuǎn)換"); hsErrCode.Add("534", "認(rèn)證機(jī)制過(guò)于
15、簡(jiǎn)單"); hsErrCode.Add("538", "當(dāng)前請(qǐng)求的認(rèn)證機(jī)制需要加密"); hsErrCode.Add("454", "臨時(shí)認(rèn)證失敗"); hsErrCode.Add("530", "需要認(rèn)證"); hsRigCode.Add("220", "服務(wù)就緒"); hsRigCode.Add("250", "要求的郵件操作完成"); hsRigCode.Add("251
16、", "用戶非本地,將轉(zhuǎn)發(fā)向<forward-path>"); hsRigCode.Add("354", "開始郵件輸入,以<CRLF>.<CRLF>結(jié)束"); hsRigCode.Add("221", "服務(wù)關(guān)閉傳輸信道"); hsRigCode.Add("334", "服務(wù)器響應(yīng)驗(yàn)證Base64字符串"); hsRigCode.Add("235", "驗(yàn)證成功");
17、#endregion #region Base64EnCode 字符串轉(zhuǎn)換為base64碼 / <summary> / 字符串轉(zhuǎn)換為base64碼 / </summary> / <param name="strValue"></param> / <returns></returns> private string Base64EnCode(string strValue) byte barray; barray = Encoding.Default.GetBytes(strValue); return
18、Convert.ToBase64String(barray); #endregion #region Base64DeCode base64碼轉(zhuǎn)換為普通字符 / <summary> / 將Base64字符串解碼為普通字符串 / </summary> / <param name="strValue"></param> / <returns></returns> private string Base64DeCode(string strValue) byte barray; barray = Conver
19、t.FromBase64String(strValue); return Encoding.Default.GetString(barray); #endregion #region MailToAdd 添加收件人 / <summary> / 添加收件人 / </summary> / <param name="varMailToAddress"></param> public void MailToAdd(string strMailToAddress) _listMailTo.Add(strMailToAddress); #
20、endregion #region MailToAdd 添加一組收件人 / <summary> / 添加一組收件人 / </summary> / <param name="strMailAddress"></param> public void MailToAdd(string strMailAddress) foreach (string str in strMailAddress) MailToAdd(str); #endregion #region MailToClear 清空收件人 / <summary>
21、/ 清空收件人 / </summary> public void MailToClear() _listMailTo.Clear(); #endregion #region MailccToAdd 添加抄送人 / <summary> / 添加抄送人 / </summary> / <param name="strMialAddress"></param> public void MailccToAdd(string strMialAddress) _listMailccTo.Add(strMialAddress);
22、#endregion #region MailccToAdd 添加一組抄送人 / <summary> / 添加一組抄送人 / </summary> / <param name="strMailAddress"></param> public void MailccToAdd(string strMailAddress) foreach (string str in strMailAddress) MailccToAdd(str); #endregion #region MailccToClear 清空抄送人 / <sum
23、mary> / 清空抄送人 / </summary> public void MailccToClear() _listMailccTo.Clear(); #endregion #region AttachmentAdd 郵件添加附件 / <summary> / 郵件添加附件 / </summary> / <param name="strFilePath"></param> public void AttachmentAdd(string strFilePath) _listAttachments.Add(s
24、trFilePath); #endregion #region AttachmentClear 清空郵件附件 / <summary> / 清空郵件附件 / </summary> public void AttachmentClear() _listAttachments.Clear(); #endregion #region GetFileStream 獲取附件文件流 / <summary> / 獲取附件文件流 / </summary> / <param name="strFilePath"></param&
25、gt; / <returns></returns> private string GetFileStream(string strFilePath) FileStream file = new FileStream(strFilePath, System.IO.FileMode.Open); byte byStream = new byteSystem.Convert.ToInt32(file.Length); file.Read(byStream, 0, byStream.Length); file.Close(); return (System.Convert.To
26、Base64String(byStream); #endregion #region SendStream 向SMTP服務(wù)器發(fā)送數(shù)據(jù) / <summary> / 向SMTP服務(wù)器發(fā)送數(shù)據(jù) / </summary> / <param name="strCmd"></param> / <returns></returns> private bool SendStream(string strCmd) byte SendBuffer; SendBuffer = Encoding.Default.GetByte
27、s(strCmd); try NetStream.Write(SendBuffer, 0, SendBuffer.Length); return true; catch (Exception ex) ErrMsg = "網(wǎng)絡(luò)連接錯(cuò)誤:" + ex.Message; return false; #endregion #region ReceiveStream 接收SMTP服務(wù)器返回?cái)?shù)據(jù) / <summary> / 接收SMTP服務(wù)器返回?cái)?shù)據(jù) / </summary> / <returns></returns> private s
28、tring ReceiveStream() int StreamSize; string ReturnStream = "" byte ReadBuffer = new byte1024; try StreamSize = NetStream.Read(ReadBuffer, 0, ReadBuffer.Length); if (StreamSize != 0) ReturnStream = Encoding.Default.GetString(ReadBuffer).Substring(0, StreamSize); catch (Exception ex) ErrMsg
29、 = "網(wǎng)絡(luò)連接錯(cuò)誤:" + ex.Message; return ReturnStream; #endregion #region CheckCommand 校驗(yàn)數(shù)據(jù)發(fā)送狀態(tài) / <summary> / 校驗(yàn)數(shù)據(jù)發(fā)送狀態(tài) / </summary> / <param name="strCmd"></param> / <returns></returns> private bool CheckCommand(string strCmd) if (SendStream(strCmd) s
30、tring strReturn = ReceiveStream(); if (strReturn = "") return false; string strReturnCode = strReturn.Substring(0, 3); if (hsRigCodestrReturnCode != null) return true; else if (hsErrCodestrReturnCode != null) ErrMsg += (strReturnCode + hsErrCodestrReturnCode.ToString(); ErrMsg += CRLF; els
31、e ErrMsg += strReturn; return false; else return false; private bool CheckCommand(string strCmds) for (int i = 0; i < strCmds.Length; i+) if (CheckCommand(strCmdsi) continue; else return false; return true; #endregion #region SendMail 發(fā)送郵件 / <summary> / 發(fā)送郵件 / </summary> / <returns
32、></returns> private bool SendMail() /連接網(wǎng)絡(luò) try client = new TcpClient(_strSmtpServer, _intPort); catch (Exception ex) ErrMsg += ex.Message; return false; NetStream = client.GetStream(); /驗(yàn)證網(wǎng)絡(luò)連接是否正確 if (hsRigCodeReceiveStream().Substring(0, 3) = null) ErrMsg += "網(wǎng)絡(luò)連接失敗" return false
33、; string SendCmdStrings; string SendCmdString; /進(jìn)行SMTP驗(yàn)證 if (UserName != "") SendCmdStrings = new String4; SendCmdStrings0 = "EHLO " + _strSmtpServer + CRLF; SendCmdStrings1 = "AUTH LOGIN" + CRLF; SendCmdStrings2 = Base64EnCode(UserName) + CRLF; SendCmdStrings3 = Base64
34、EnCode(PassWord) + CRLF; if (!CheckCommand(SendCmdStrings) return false; else SendCmdString = "HELO " + _strSmtpServer + CRLF; if (!CheckCommand(SendCmdString) return false; SendCmdString = "MAIL FROM:<" + _strMailFrom + ">" + CRLF; if (!CheckCommand(SendCmdString
35、) return false; for (int i = 0; i < _listMailTo.Count; i+) SendCmdString = "RCPT TO:<" + _listMailToi.ToString() + ">" + CRLF; if (!CheckCommand(SendCmdString) return false; SendCmdString = "DATA" + CRLF; if (!CheckCommand(SendCmdString) return false; /構(gòu)造發(fā)送數(shù)據(jù) S
36、endCmdString = "From:" + _strMailFromName + "<" + _strMailFrom + ">" + CRLF; SendCmdString += "To:<" + _listMailTo0 + ">" for (int i = 1; i < _listMailTo.Count; i+) SendCmdString += ",<" + _listMailToi.ToString() + "&
37、gt;," SendCmdString += CRLF; if (_listMailccTo.Count != 0) SendCmdString += "CC:" for (int i = 0; i < _listMailccTo.Count; i+) SendCmdString += "<" + _listMailccToi.ToString() + ">," SendCmdString += CRLF; if (_strCharSet = "") SendCmdString += &
38、quot;Subject:" + _strSubject + CRLF; else SendCmdString += "Subject:=?" + _strCharSet.ToUpper() + "?B?" + Base64EnCode(_strSubject) + "?=" + CRLF; SendCmdString += "X-Priority:" + Priority + CRLF; SendCmdString += "X-MSMail-Priority:" + Priority
39、 + CRLF; SendCmdString += "Importance:" + Priority + CRLF; SendCmdString += "X-Mailer: Huolx.Pubclass" + CRLF; SendCmdString += "MIME-Version: 1.0" + CRLF; if (_listAttachments.Count != 0) SendCmdString += "Content-Type: multipart/mixed;" + CRLF; SendCmdString
40、 += " boundary="=" + (_IsHtml ? "001_mail_part_line_01" : "002_mail_part_line_01") + "="" + CRLF + CRLF; if (_IsHtml) if (_listAttachments.Count = 0) SendCmdString += "Content-Type: multipart/alternative;" + CRLF;/內(nèi)容格式和分隔符 SendCmdString +=
41、" boundary="=001_mail_part_line_02="" + CRLF + CRLF; SendCmdString += "This is a multi-part message in MIME format." + CRLF + CRLF; else SendCmdString += "This is a multi-part message in MIME format." + CRLF + CRLF; SendCmdString += "-=001_mail_part_line_
42、01=" + CRLF; SendCmdString += "Content-Type: multipart/alternative;" + CRLF;/內(nèi)容格式和分隔符 SendCmdString += " boundary="=001_mail_part_line_02="" + CRLF + CRLF; SendCmdString += "-=001_mail_part_line_02=" + CRLF; SendCmdString += "Content-Type: text/plain
43、;" + CRLF; SendCmdString += (_strCharSet = "") ? (" charset="iso-8859-1"") : (" charset="" + _strCharSet.ToLower() + """) + CRLF; SendCmdString += "Content-Transfer-Encoding: base64" + CRLF + CRLF; SendCmdString += Base64EnCo
44、de("郵件內(nèi)容為HTML格式,請(qǐng)選擇HTML方式查看") + CRLF + CRLF; SendCmdString += "-=001_mail_part_line_02=" + CRLF; SendCmdString += "Content-Type: text/html;" + CRLF; SendCmdString += (_strCharSet = "") ? (" charset="iso-8859-1"") : (" charset="" + _strCharSet.ToLower() + """) + CRLF; SendCmdString += "Content-Transfer-Encoding: base64" + CRLF + CRLF; SendCmdString += Base64EnCode(_strBody) + CRLF + CRLF; SendCmdString += "-=001_mail_part_line_02=-" + CRLF; else if (_listAttachments.Count != 0) S
溫馨提示
- 1. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年魯人新版選修化學(xué)下冊(cè)月考試卷
- 二零二五年度國(guó)際物流運(yùn)輸服務(wù)合同14篇
- 2025版網(wǎng)絡(luò)安全風(fēng)險(xiǎn)評(píng)估與應(yīng)急預(yù)案合同4篇
- 二零二五年度木工機(jī)械操作人員勞務(wù)租賃合同4篇
- 2025年外研版選修四歷史下冊(cè)月考試卷
- 2025年湘教版九年級(jí)歷史下冊(cè)月考試卷
- 2024年度陜西省公共營(yíng)養(yǎng)師之四級(jí)營(yíng)養(yǎng)師通關(guān)提分題庫(kù)及完整答案
- 2024年度陜西省公共營(yíng)養(yǎng)師之四級(jí)營(yíng)養(yǎng)師能力測(cè)試試卷A卷附答案
- 車間的現(xiàn)代化轉(zhuǎn)型與創(chuàng)新發(fā)展思考
- 2025年蘇教版選擇性必修3歷史下冊(cè)階段測(cè)試試卷含答案
- 第十七章-阿法芙·I·梅勒斯的轉(zhuǎn)變理論
- 焊接機(jī)器人在汽車制造中應(yīng)用案例分析報(bào)告
- 合成生物學(xué)在生物技術(shù)中的應(yīng)用
- 中醫(yī)門診病歷
- 廣西華銀鋁業(yè)財(cái)務(wù)分析報(bào)告
- 無(wú)違法犯罪記錄證明申請(qǐng)表(個(gè)人)
- 大學(xué)生勞動(dòng)教育PPT完整全套教學(xué)課件
- 繼電保護(hù)原理應(yīng)用及配置課件
- 《殺死一只知更鳥》讀書分享PPT
- 蓋洛普Q12解讀和實(shí)施完整版
- 2023年Web前端技術(shù)試題
評(píng)論
0/150
提交評(píng)論