C#基于SMTP协议发送电子邮件_第1页
C#基于SMTP协议发送电子邮件_第2页
C#基于SMTP协议发送电子邮件_第3页
C#基于SMTP协议发送电子邮件_第4页
C#基于SMTP协议发送电子邮件_第5页
已阅读5页,还剩10页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、C#基于SMTP协议发送电子邮件本代码示例演示了使用TcpClient和NetWorkStream基于SMTP协议发送电子邮件的全部过程,代码在VS2010中可以直接运行调用方式如下:ClsSendMail obj = new ClsSendMail();obj.UserName = "你的邮箱"obj.PassWord = "邮箱密码"bool flag = obj.Send("smtp地址", "你的邮箱", "发送人姓名", "收件人", "抄送人"

2、,true, "主题", "邮件内容");public class ClsSendMail #region 构造函数 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 = "" /邮件服务器地址 private int _intPort = 25; /服务器端口 private string _strUserName = "" / SMTP认证时使用的用户名 private string _strPassWord = "" / SMTP认证时使用的密码 private string _strMailFrom = "" / 发件人地址 private stri

5、ng _strMailFromName = "" / 发件人姓名 private List<string> _listMailTo; / 收件人列表 private List<string> _listMailccTo; / 抄送收件人列表 private bool _IsHtml = false; / 是否Html邮件 private string _strPriority = "Normal" / 邮件发送优先级 private string _strSubject = "" / 邮件主题 private

6、string _strBody = "" / 邮件正文 private List<string> _listAttachments; / 邮件附件列表 private string _strCharSet = "GB2312" / 设定语言代码,默认设定为GB2312 private TcpClient client; / TcpClient对象,用于连接服务器 private NetworkStream NetStream; / NetworkStream对象 private Hashtable hsErrCode = new Hashta

7、ble(); / SMTP错误代码哈希表 private Hashtable hsRigCode = new Hashtable(); / SMTP正确代码哈希表 private string CRLF = "rn" /回车符号 private string ErrMsg = "" /记录错误消息 #region MailPriority / <summary> / 邮件发送优先级(可设置为"High","Normal","Low"或"1","3&quo

8、t;,"5") / </summary> public enum MailPriority High, Normal, Low #endregion #region SmtpServer / <summary> / 邮件服务器地址 / </summary> public string SmtpServer get return this._strSmtpServer; set this._strSmtpServer = value; #endregion #region Port / <summary> / 服务器端口 / &

9、lt;/summary> public int Port get return this._intPort; set this._intPort = value; #endregion #region UserName / <summary> / SMTP认证时使用的用户名 / </summary> public string UserName get return this._strUserName; set this._strUserName = value; #endregion #region PassWord / <summary> / SM

10、TP认证时使用的密码 / </summary> public string PassWord get return this._strPassWord; set this._strPassWord = value; #endregion #region Priority / <summary> / 优先级 / </summary> public string Priority get return this._strPriority; set this._strPriority = value; #endregion #region CharSet / &l

11、t;summary> / 设定语言代码,默认设定为GB2312 / </summary> public string CharSet get return this._strCharSet; set this._strCharSet = value; #endregion #endregion #region 成员函数 #region InitSmtpCode 初始化SMTP服务器返回结果Hash表 / <summary> / 初始化SMTP服务器返回结果Hash表 / </summary> private void InitSmtpCode() hs

12、ErrCode.Add("500", "邮箱地址错误"); hsErrCode.Add("501", "参数格式错误"); hsErrCode.Add("502", "命令不可实现"); hsErrCode.Add("503", "服务器需要SMTP验证"); hsErrCode.Add("504", "命令参数不可实现"); hsErrCode.Add("421", &quo

13、t;服务未就绪,关闭传输信道"); hsErrCode.Add("450", "要求的邮件操作未完成,邮箱不可用(例如,邮箱忙)"); hsErrCode.Add("550", "要求的邮件操作未完成,邮箱不可用(例如,邮箱未找到,或不可访问)"); hsErrCode.Add("451", "放弃要求的操作;处理过程中出错"); hsErrCode.Add("551", "用户非本地,请尝试<forward-path>&q

14、uot;); hsErrCode.Add("452", "系统存储不足,要求的操作未执行"); hsErrCode.Add("552", "过量的存储分配,要求的操作未执行"); hsErrCode.Add("553", "邮箱名不可用,要求的操作未执行(例如邮箱格式错误)"); hsErrCode.Add("432", "需要一个密码转换"); hsErrCode.Add("534", "认证机制过于简单

15、"); hsErrCode.Add("538", "当前请求的认证机制需要加密"); hsErrCode.Add("454", "临时认证失败"); hsErrCode.Add("530", "需要认证"); hsRigCode.Add("220", "服务就绪"); hsRigCode.Add("250", "要求的邮件操作完成"); hsRigCode.Add("251&q

16、uot;, "用户非本地,将转发向<forward-path>"); hsRigCode.Add("354", "开始邮件输入,以<CRLF>.<CRLF>结束"); hsRigCode.Add("221", "服务关闭传输信道"); hsRigCode.Add("334", "服务器响应验证Base64字符串"); hsRigCode.Add("235", "验证成功"); #e

17、ndregion #region Base64EnCode 字符串转换为base64码 / <summary> / 字符串转换为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码转换为普通字符 / <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服务器发送数据 / <summary> / 向SMTP服务器发送数据 / </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 = "网络连接错误:" + ex.Message; return false; #endregion #region ReceiveStream 接收SMTP服务器返回数据 / <summary> / 接收SMTP服务器返回数据 / </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、 "网络连接错误:" + ex.Message; return ReturnStream; #endregion #region CheckCommand 校验数据发送状态 / <summary> / 校验数据发送状态 / </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 发送邮件 / <summary> / 发送邮件 / </summary> / <returns&g

32、t;</returns> private bool SendMail() /连接网络 try client = new TcpClient(_strSmtpServer, _intPort); catch (Exception ex) ErrMsg += ex.Message; return false; NetStream = client.GetStream(); /验证网络连接是否正确 if (hsRigCodeReceiveStream().Substring(0, 3) = null) ErrMsg += "网络连接失败" return false;

33、string SendCmdStrings; string SendCmdString; /进行SMTP验证 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; /构造发送数据 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;/内容格式和分隔符 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;/内容格式和分隔符 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、("邮件内容为HTML格式,请选择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等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论