版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
1、C#基于SMTP協(xié)議發(fā)送電子郵件本代碼示例演示了使用TcpClient和NetWorkStream基于SMTP協(xié)議發(fā)送電子郵件的全部過程,代碼在VS2010中可以直接運(yùn)行調(diào)用方式如下:ClsSendMail obj = new ClsSendMail();obj.UserName = "你的郵箱"obj.PassWord = "郵箱密碼"bool flag = obj.Send("smtp地址", "你的郵箱", "發(fā)送人姓名", "收件人", "抄送人"
2、,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, str
3、ing 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>(); InitSmtp
4、Code(); #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 stri
5、ng _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 = "" / 郵件主題 private
6、string _strBody = "" / 郵件正文 private List<string> _listAttachments; / 郵件附件列表 private string _strCharSet = "GB2312" / 設(shè)定語言代碼,默認(rèn)設(shè)定為GB2312 private TcpClient client; / TcpClient對(duì)象,用于連接服務(wù)器 private NetworkStream NetStream; / NetworkStream對(duì)象 private Hashtable hsErrCode = new Hashta
7、ble(); / 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&quo
8、t;,"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、lt;/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> / SM
10、TP認(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 / &l
11、t;summary> / 設(shè)定語言代碼,默認(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() hs
12、ErrCode.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", &quo
13、t;服務(wù)未就緒,關(guān)閉傳輸信道"); hsErrCode.Add("450", "要求的郵件操作未完成,郵箱不可用(例如,郵箱忙)"); hsErrCode.Add("550", "要求的郵件操作未完成,郵箱不可用(例如,郵箱未找到,或不可訪問)"); hsErrCode.Add("451", "放棄要求的操作;處理過程中出錯(cuò)"); hsErrCode.Add("551", "用戶非本地,請(qǐng)嘗試<forward-path>&q
14、uot;); hsErrCode.Add("452", "系統(tǒng)存儲(chǔ)不足,要求的操作未執(zhí)行"); hsErrCode.Add("552", "過量的存儲(chǔ)分配,要求的操作未執(zhí)行"); hsErrCode.Add("553", "郵箱名不可用,要求的操作未執(zhí)行(例如郵箱格式錯(cuò)誤)"); hsErrCode.Add("432", "需要一個(gè)密碼轉(zhuǎn)換"); hsErrCode.Add("534", "認(rèn)證機(jī)制過于簡單
15、"); 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&q
16、uot;, "用戶非本地,將轉(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)證成功"); #e
17、ndregion #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 Co
18、nvert.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 = Convert.
19、FromBase64String(strValue); return Encoding.Default.GetString(barray); #endregion #region MailToAdd 添加收件人 / <summary> / 添加收件人 / </summary> / <param name="varMailToAddress"></param> public void MailToAdd(string strMailToAddress) _listMailTo.Add(strMailToAddress); #en
20、dregion #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); #e
22、ndregion #region MailccToAdd 添加一組抄送人 / <summary> / 添加一組抄送人 / </summary> / <param name="strMailAddress"></param> public void MailccToAdd(string strMailAddress) foreach (string str in strMailAddress) MailccToAdd(str); #endregion #region MailccToClear 清空抄送人 / <summa
23、ry> / 清空抄送人 / </summary> public void MailccToClear() _listMailccTo.Clear(); #endregion #region AttachmentAdd 郵件添加附件 / <summary> / 郵件添加附件 / </summary> / <param name="strFilePath"></param> public void AttachmentAdd(string strFilePath) _listAttachments.Add(str
24、FilePath); #endregion #region AttachmentClear 清空郵件附件 / <summary> / 清空郵件附件 / </summary> public void AttachmentClear() _listAttachments.Clear(); #endregion #region GetFileStream 獲取附件文件流 / <summary> / 獲取附件文件流 / </summary> / <param name="strFilePath"></param>
25、; / <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.ToBa
26、se64String(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.GetBytes(
27、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 str
28、ing 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) str
30、ing 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; else
31、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&g
32、t;</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 = Base64En
34、Code(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ù) Sen
36、dCmdString = "From:" + _strMailFromName + "<" + _strMailFrom + ">" + CRLF; SendCmdString += "To:<" + _listMailTo0 + ">" for (int i = 1; i < _listMailTo.Count; i+) SendCmdString += ",<" + _listMailToi.ToString() + ">
37、;," SendCmdString += CRLF; if (_listMailccTo.Count != 0) SendCmdString += "CC:" for (int i = 0; i < _listMailccTo.Count; i+) SendCmdString += "<" + _listMailccToi.ToString() + ">," SendCmdString += CRLF; if (_strCharSet = "") SendCmdString += &qu
38、ot;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 += &q
41、uot; 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_01
42、=" + 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、quot; + CRLF; SendCmdString += (_strCharSet = "") ? (" charset="iso-8859-1"") : (" charset="" + _strCharSet.ToLower() + """) + CRLF; SendCmdString += "Content-Transfer-Encoding: base64" + CRLF + CRLF; SendCmdString += Base64EnCode
44、("郵件內(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. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(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ì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 二零二五年度個(gè)人承包物流配送合同3篇
- 2025涉外合同的相關(guān)事項(xiàng)
- 二零二五年度幼兒園園長任期教育信息化與智慧校園建設(shè)合同3篇
- 2025年度養(yǎng)豬場養(yǎng)殖保險(xiǎn)與風(fēng)險(xiǎn)防控合作協(xié)議3篇
- 2025年度店面轉(zhuǎn)讓定金及后續(xù)培訓(xùn)服務(wù)協(xié)議3篇
- 2025年度農(nóng)副產(chǎn)品電商平臺(tái)售后服務(wù)合作協(xié)議3篇
- 二零二五年度物流倉儲(chǔ)經(jīng)營權(quán)承包管理協(xié)議書3篇
- 二零二五年度農(nóng)村房屋買賣與景觀設(shè)計(jì)合同2篇
- 2025年度專利技術(shù)許可及推廣應(yīng)用協(xié)議3篇
- 二零二五年度內(nèi)墻膩?zhàn)邮┕づc智能家居安防系統(tǒng)合同3篇
- 《調(diào)水工程設(shè)計(jì)導(dǎo)則SL-T430-20XX-條文說明》
- 第二單元自測卷(試題)2023-2024學(xué)年統(tǒng)編版語文四年級(jí)下冊(cè)
- 六年級(jí)上冊(cè)數(shù)學(xué)應(yīng)用題分類練習(xí)100道
- 土方開挖過程中的文物保存方案
- 臨時(shí)安全用電要求安全培訓(xùn)
- 水稻田稻鴨共棲技術(shù)要點(diǎn)
- 肺功能科室工作報(bào)告
- 如何訓(xùn)練寶寶獨(dú)立就寢
- 血常規(guī)報(bào)告單
- 寶寶大便觀察及護(hù)理課件
- 學(xué)校最小應(yīng)急單元應(yīng)急預(yù)案
評(píng)論
0/150
提交評(píng)論