位置:海鸟网 > IT > ASP.NET >

C#写的支持SMTP验证的发送邮件组件(1)

这是我学C#后写的第一个比较拿得出手的东西,肯定有很多错误之处,还望各位高手指正。


写它的原因就是.net自带的SmtpMail不支持SMTP认证(说句题外话,我真很奇怪, 从ASP到ASP.NET,M$的邮件组件老是慢半拍,ASP中的CDONTS难得能有正常使用的, 到了.NET时代,SMTP服务器基本都得验证才能用,.NET的SmtpMail又不支持验证, 真是~~~),我费了好几天功夫才弄明白怎样把原来的Jmail怎么弄到.NET下用, 可用起来还是比较麻烦,正好买了本《C#网络程序设计》,作为实践项目,也是为了 让自己以后轻松一点,我写了这个东西。


程序架构可能有些乱,都是原来写ASP时留下的毛病,如果那位能帮我弄得整齐一点,小弟感激不尽。


欢迎大家提出修改建议,或者自行修改,最好能把修改稿Mail给我一份,让我也学习学习 ^_^。

完整的源代码和编译好的DLL可以从下面的URL下载。
?classlevel=3&classname=.net技术&l2classname=ESmtpmail&articleid=-486856519

下面开始贴源代码。


using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Collections;

namespace Huolx.Pubclass
{
    /// <summary>
    /// <para>支持SMTP服务器认证的邮件发送类</para>
    /// <para></para>
    /// <para>ver 1.0B</para>
    /// <para>属性和方法设置类似于Jmail。</para>
    /// <para></para>
    /// <para>Huolx(flycloud@btamail.net.cn)版权所有,转载请保留。</para>
    /// </summary>
    /// <remarks>
    /// <para>这是我学C#后写的第一个比较拿得出手的东西,肯定有很多错误之处,还望各位高手指正。</para>
    /// <para></para>
    /// <para>写它的原因就是.net自带的SmtpMail不支持SMTP认证(说句题外话,我真很奇怪,
    /// 从ASP到ASP.NET,M$的邮件组件老是慢半拍,ASP中的CDONTS难得能有正常使用的,
    /// 到了.NET时代,SMTP服务器基本都得验证才能用,.NET的SmtpMail又不支持验证,
    /// 真是~~~),我费了好几天功夫才弄明白怎样把原来的Jmail怎么弄到.NET下用,
    /// 可用起来还是比较麻烦,正好买了本《C#网络程序设计》,作为实践项目,也是为了
    /// 让自己以后轻松一点,我写了这个东西。</para>
    /// <para></para>
    /// <para>程序架构可能有些乱,都是原来写ASP时留下的毛病,如果那位能帮我弄得整齐一点,小弟感激不尽。</para>
    /// <para></para>
    /// <para>欢迎大家提出修改建议,或者自行修改,最好能把修改稿Mail给我一份,让我也学习学习 ^_^。</para>
    /// </remarks>
    public class ESmtpMail
    {

        /// <summary>
        /// 设定语言代码,默认设定为GB2312,如不需要可设置为""
        /// </summary>
        public string Charset="GB2312";

        /// <summary>
        /// 发件人地址
        /// </summary>
        public string From="";

        /// <summary>
        /// 发件人姓名
        /// </summary>
        public string FromName="";

        /// <summary>
        /// 回复邮件地址
        /// </summary>
        public string ReplyTo="";

        /// <summary>
        /// 邮件服务器域名
        /// </summary>    
        private string mailserver="";

        /// <summary>
        /// 邮件服务器域名和验证信息
        /// 形如:"user:pass@:25",也可省略次要信息。如"user:pass@"或""
        /// </summary>    
        public string MailDomain
        {
            set
            {
                string maidomain=value.Trim();
                int tempint;

                if(maidomain!="")
                {
                    tempint=maidomain.IndexOf("@");
                    if(tempint!=-1)
                    {
                        string up=maidomain.Substring(0,tempint);
                        MailServerUserName=up.Substring(0,up.IndexOf(":"));
                        MailServerPassWord=up.Substring(up.IndexOf(":")+1,up.Length-up.IndexOf(":")-1);
                        string ms=maidomain.Substring(tempint+1,maidomain.Length-tempint-1);
                        tempint=ms.IndexOf(":");
                        if(tempint!=-1)
                        {
                            mailserver=ms.Substring(0,tempint);
                            mailserverport=System.Convert.ToInt32(ms.Substring(tempint+1,ms.Length-tempint-1));
                        }
                    }
                    else
                    {
                        tempint=maidomain.IndexOf(":");
                        if(tempint!=-1)
                        {
                            mailserver=maidomain.Substring(0,tempint);
                            mailserverport=System.Convert.ToInt32(maidomain.Substring(tempint+1,maidomain.Length-tempint-1));
                        }
                        else
                        {
                            mailserver=maidomain;

                        }

                    }
                }

            }
        }

        /// <summary>
        /// 邮件服务器端口号
        /// </summary>    
        private int mailserverport=25;

        /// <summary>
        /// 邮件服务器端口号
        /// </summary>    
        public int MailDomainPort
        {
            set
            {
                mailserverport=value;
            }
        }


        /// <summary>
        /// 是否需要SMTP验证
        /// </summary>        
        private bool ESmtp=false;

        /// <summary>
        /// SMTP认证时使用的用户名
        /// </summary>
        private string username="";

        /// <summary>
        /// SMTP认证时使用的用户名
        /// </summary>
        public string MailServerUserName
        {
            set
            {
                if(value.Trim()!="")
                {
                    username=value.Trim();
                    ESmtp=true;
                }
                else
                {
                    username="";
                    ESmtp=false;
                }
            }
        }

        /// <summary>
        /// SMTP认证时使用的密码
        /// </summary>
        private string password="";

        /// <summary>
        /// SMTP认证时使用的密码
        /// </summary>
        public string MailServerPassWord
        {
            set
            {
                password=value;
            }
        }    

        /// <summary>
        /// 邮件主题
        /// </summary>        
        public string Subject="";
        
        /// <summary>
        /// 是否Html邮件
        /// </summary>        
        public bool Html=false;

        /// <summary>
        /// 邮件正文
        /// </summary>        
        public string Body="";

        /// <summary>
        /// 收件人列表
        /// </summary>
        private Hashtable Recipient=new Hashtable();

        /// <summary>
        /// 密送收件人列表
        /// </summary>
        private Hashtable RecipientBCC=new Hashtable();

        /// <summary>
        /// 邮件发送优先级,可设置为"High","Normal","Low"或"1","3","5"
        /// </summary>
        private string priority="Normal";

        /// <summary>
        /// 邮件发送优先级,可设置为"High","Normal","Low"或"1","3","5"
        /// </summary>
        public string Priority
        {
            set
            {
                switch(value.ToLower())
                {
                    case "high":
                        priority="High";
                        break;

                    case "1":
                        priority="High";
                        break;

                    case "normal":
                        priority="Normal";
                        break;

                    case "3":
                        priority="Normal";
                        break;

                    case "low":
                        priority="Low";
                        break;

                    case "5":
                        priority="Low";
                        break;

                    default:
                        priority="Normal";
                        break;
                }
            }
        }


        /// <summary>
        /// 错误消息反馈
        /// </summary>
        private string errmsg;

        /// <summary>
        /// 错误消息反馈
        /// </summary>        
        public string ErrorMessage
        {
            get
            {
                return errmsg;
            }
        }



        /// <summary>
        /// 服务器交互记录
        /// </summary>
        private string logs="";

        /// <summary>
        /// 服务器交互记录,如发现本组件不能使用的SMTP服务器,请将出错时的Logs发给我(flycloud@btamail.net.cn),我将尽快查明原因。
        /// </summary>
        public string Logs
        {
            get
            {
                return logs;
            }
        }
        

        private string enter="\r\n";
        /// <summary>
        /// TcpClient对象,用于连接服务器
        /// </summary>    
        private TcpClient tc;

        /// <summary>
        /// NetworkStream对象
        /// </summary>    
        private NetworkStream ns;

        /// <summary>
        /// SMTP错误代码哈希表
        /// </summary>
        private Hashtable ErrCodeHT = new Hashtable();

        /// <summary>
        /// SMTP正确代码哈希表
        /// </summary>
        private Hashtable RightCodeHT = new Hashtable();

        /// <summary>
        /// SMTP回应代码哈希表
        /// </summary>
        private void SMTPCodeAdd()
        {
            ErrCodeHT.Add("500","邮箱地址错误");
            ErrCodeHT.Add("501","参数格式错误");
            ErrCodeHT.Add("502","命令不可实现");
            ErrCodeHT.Add("503","服务器需要SMTP验证");
            ErrCodeHT.Add("504","命令参数不可实现");
            ErrCodeHT.Add("421","服务未就绪,关闭传输信道");
            ErrCodeHT.Add("450","要求的邮件操作未完成,邮箱不可用(例如,邮箱忙)");
            ErrCodeHT.Add("550","要求的邮件操作未完成,邮箱不可用(例如,邮箱未找到,或不可访问)");
            ErrCodeHT.Add("451","放弃要求的操作;处理过程中出错");
            ErrCodeHT.Add("551","用户非本地,请尝试<forward-path>");
            ErrCodeHT.Add("452","系统存储不足,要求的操作未执行");
            ErrCodeHT.Add("552","过量的存储分配,要求的操作未执行");
            ErrCodeHT.Add("553","邮箱名不可用,要求的操作未执行(例如邮箱格式错误)");
            ErrCodeHT.Add("432","需要一个密码转换");
            ErrCodeHT.Add("534","认证机制过于简单");
            ErrCodeHT.Add("538","当前请求的认证机制需要加密");
            ErrCodeHT.Add("454","临时认证失败");
            ErrCodeHT.Add("530","需要认证");

            RightCodeHT.Add("220","服务就绪");
            RightCodeHT.Add("250","要求的邮件操作完成");
            RightCodeHT.Add("251","用户非本地,将转发向<forward-path>");
            RightCodeHT.Add("354","开始邮件输入,以<CRLF>.<CRLF>结束");
            RightCodeHT.Add("221","服务关闭传输信道");
            RightCodeHT.Add("334","服务器响应验证Base64字符串");
            RightCodeHT.Add("235","验证成功");
        }


        /// <summary>
        /// 将字符串编码为Base64字符串
        /// </summary>
        /// <param name="estr">要编码的字符串</param>
        private string Base64Encode(string estr)
        {
            byte[] barray;
            barray=Encoding.Default.GetBytes(estr);
            return Convert.ToBase64String(barray);
        }


        /// <summary>
        /// 将Base64字符串解码为普通字符串
        /// </summary>
        /// <param name="dstr">要解码的字符串</param>
        private string Base64Decode(string dstr)
        {
            byte[] barray;
            barray=Convert.FromBase64String(dstr);
            return Encoding.Default.GetString(barray);
        }


        public ESmtpMail()
        {
        }

        ~ESmtpMail()
        {
        }


        /// <summary>
        /// 收件人姓名
        /// </summary>    
        public string RecipientName="";


        private int RecipientNum=0;//收件人数量
        private int RecipientBCCNum=0;//密件收件人数量

        /// <summary>
        /// 添加一个收件人
        /// </summary>    
        /// <param name="str">收件人地址</param>
        public bool AddRecipient(string str)
        {
            str=str.Trim();
            if(str==null||str==""||str.IndexOf("@")==-1)
                return true;
            if(RecipientNum<10)
            {
                Recipient.Add(RecipientNum,str);
                RecipientNum++;
                return true;
            }
            else
            {
                errmsg+="收件人过多";
                return false;
            }
        }


        /// <summary>
        /// 添加一组收件人(不超过10个),参数为字符串数组
        /// </summary>
        /// <param name="str">保存有收件人地址的字符串数组(不超过10个)</param>    
        public bool AddRecipient(string[] str)
        {
            for(int i=0;i<str.Length;i++)
            {
                if(!AddRecipient(str[i]))
                {
                    return false;
                }
            }
            return true;
        }


        /// <summary>
        /// 添加一个密件收件人
        /// </summary>
        /// <param name="str">收件人地址</param>
        public bool AddRecipientBCC(string str)
        {
            if(str==null||str.Trim()=="")
                return true;
            if(RecipientBCCNum<10)
            {
                RecipientBCC.Add(RecipientBCCNum,str);
                RecipientBCCNum++;
                return true;
            }
            else
            {
                errmsg+="收件人过多";
                return false;
            }
        }


        /// <summary>
        /// 添加一组密件收件人(不超过10个),参数为字符串数组
        /// </summary>    
        /// <param name="str">保存有收件人地址的字符串数组(不超过10个)</param>
        public bool AddRecipientBCC(string[] str)
        {
            for(int i=0;i<str.Length;i++)
            {
                if(!AddRecipientBCC(str[i]))
                {
                    return false;
                }
            }
            return true;
        }


        /// <summary>
        /// 发送SMTP命令
        /// </summary>    
        private bool SendCommand(string Command)
        {
            byte[]  WriteBuffer;
            if(Command==null||Command.Trim()=="")
            {
                return true;
            }
            logs+=Command;
            WriteBuffer = Encoding.Default.GetBytes(Command);
            try
            {
                ns.Write(WriteBuffer,0,WriteBuffer.Length);
            }
            catch
            {
                errmsg="网络连接错误";
                return false;
            }
            return true;
        }