您好,欢迎来到年旅网。
搜索
您的当前位置:首页邮件服务器

邮件服务器

来源:年旅网
smtp邮件服务器:用c#写的smtp邮件发送类(2)

疯狂代码 http://CrazyCoder.cn/ ĵ:http:/CrazyCoder.cn/DotNet/Article475.html

    ///

      /// 向SMTP发送命令      ///  

    ///       private

     sendCommand(

     cmd,bool isMailData )      {

      ( cmd!=null && cmd.Trim( )!=       .Empty )       {

         cmd_b=null;

        ( !isMailData )//不是邮件数据         cmdCRLF;         logscmd;

        //开始写入邮件数据         ( !isMailData )         {

          cmd_b=Encoding.ASCII.GetBytes( cmd );           ns.Write( cmd_b,0,cmd_b.Length );         }

        {

          cmd_b=Encoding.GetEncoding(

          this.mailEncodingName ).GetBytes( cmd );

          ns.BeginWrite( cmd_b,0,cmd_b.Length, AsyncCallback(           this.asyncCallBack ),null );         }

        //读取服务器响应

        StreamReader reader= StreamReader( ns );

         response=reader.ReadLine( );         logsresponse+CRLF;         //检查状态码

         statusCode=response.Sub         ( 0,3 );

        bool isExist=false;

        bool isRightCode=true;         foreach(          err in

        this.errorCodes.Keys )         {

          ( statusCodeerr )           {

            isExist=true;

            isRightCode=false;             ;           }         }

        foreach(          right in

        this.rightCodes.Keys )         {

          ( statusCoderight )           {

            isExist=true;             ;           }         }

        //根据状态码来处理下步动作         ( !isExist ) //不是合法SMTP主机         {

          this.Error( \"不是合法SMTP主机,或服务器拒绝服务\" );         }

         ( !isRightCode )//命令没能成功执行         {

          this.Error( statusCode+\":\"+

          this.errorCodes[statusCode] );         }

         //命令成功执行         {

          this.errorMessage=\"\";         }

         response;       }

      {

         null;       }     }

    ///

 

    /// 通过auth login方式登陆smtp服务器      ///

 

    private void landingByLogin( )      {

       baseUserId=

      this.convertBaseString(       this.UserID,\"ASCII\" );

       basePass=

      this.convertBaseString(       this.Password,\"ASCII\" );       //握手

      this.sendCommand( \"helo \"+       this.serverName,false );       //开始登陆

      this.sendCommand( \"auth login\

      this.sendCommand( baseUserId,false );

      this.sendCommand( basePass,false );     }

    ///

 

    /// 通过auth plain方式登陆服务器      ///

 

    private void landingByPlain( )      {

       NULL=( (       char )0 ).( );

       loginStr=NULL+       this.UserID+NULL+       this.Password;

       baseLoginStr=

      this.convertBaseString( loginStr,\"ASCII\" );       //握手

      this.sendCommand( \"helo \"+       this.serverName,false );       //登陆

      this.sendCommand( baseLoginStr,false );     }

    ///

 

    /// 通过auth CRAM-MD5方式登陆      ///

 

    private void landingByCRAMMD5( )      {

      //握手

      this.sendCommand( \"helo \"+       this.serverName,false );       //登陆

       response=

      this.sendCommand( \"auth CRAM-MD5\      //得到服务器返回标识

       identier=response.Remove( 0,4 );       //用MD5加密标识

      KSN_MACTripleDES mac= KSN_MACTripleDES( );       mac.Key=

      this.Password;

      mac.Data=Encoding.ASCII.GetBytes( identier );

       hash=mac.GetHashValue( );       //发送用户帐号信息       this.sendCommand(

      this.UserID+\" \"+hash,false );     }

    ///

      /// 发送邮件 

    ///

      ///  

    public bool SendMail( MailMessage mail )      {

      bool isSended=true;       try       {

        //检测发送邮件必要条件         ( mail.Sendernull )         {

          this.Error( \"没有设置发信人\" );         }

        ( mail.Receivers.Count0 )         {

          this.Error( \"至少要有个收件人\" );         }         (

        this.SmtpValidateType!=SmtpValidateTypes.None )         {           (

          this.useridnull ||           this.passwordnull )           {

            this.Error( \"当前设置需要smtp验证,但是没有给出登陆帐号\" );           }         }

        //开始登陆         switch(

        this.SmtpValidateType )         {

           SmtpValidateTypes.None:           this.sendCommand( \"helo \"+           this.serverName,false );           ;

           SmtpValidateTypes.Login:           this.landingByLogin( );           ;

           SmtpValidateTypes.Plain:           this.landingByPlain( );           ;

           SmtpValidateTypes.CRAMMD5:           this.landingByCRAMMD5( );           ;

          default:           ;         }

        //化邮件会话( 对应SMTP命令mail )

        this.sendCommand( \"mail from:<\"+mail.Sender+\">\        //标识收件人( 对应SMTP命令Rcpt )         foreach(

         receive in mail.Receivers )         {

          this.sendCommand( \"rcpt to:<\"+receive+\">\        }

        //标识开始输入邮件内容( Data )         this.sendCommand( \"data\        //开始编写邮件内容

         message=\"Subject:\"+mail.Subject+CRLF;         message\"X-mailer:\"+mail.XMailer+CRLF;

        message\"MIME-Version:1.0\"+CRLF;         ( mail.Attachments.Count0 )//没有附件         {

          ( mail.MailTypeMailTypes.Text ) //文本格式           {

            message\"Content-Type:text/plain;             \"+CRLF+\" \".PadRight( 8,' ' )+\"             char=\"\"+

            mail.MailEncoding.( )+\"\"\"+CRLF;

            message\"Content-Transfer-Encoding:base\"+CRLF+CRLF;             ( mail.MailBody!=null )

            messageConvert.ToBaseString( mail.MailBody,0,mail.MailBody.Length)+CRLF+CRLF+CRLF+\".\"+CRLF;           }

          //Html格式           {

            message\"Content-Type:multipart/alertnative;             \"+CRLF+\" \".PadRight( 8,' ' )+\"boundary\"

            +\"=\"=003_Dragon310083331177_=\"\"+CRLF+CRLF+CRLF;

            message\"This is a multi-part message in MIME format\"+CRLF+CRLF;             message\"--=003_Dragon310083331177_=\"+CRLF;             message\"Content-Type:text/html;             \"+CRLF+\" \".PadRight( 8,' ' )+\"             char=\"\"+

            mail.MailEncoding.( ).ToLower( )+\"\"\"+CRLF;

            message\"Content-Transfer-Encoding:base\"+CRLF+CRLF;             ( mail.MailBody!=null )

            messageConvert.ToBaseString( mail.MailBody,0,mail.MailBody.Length)+CRLF+CRLF;

            message\"--=003_Dragon310083331177_=--\"+CRLF+CRLF+CRLF+\".\"+CRLF;           }         }

        //有附件         {

          //处理要在邮件中显示每个附件数据

          StringCollection attatchmentDatas= StringCollection( );

          foreach(

           path in mail.Attachments )           {

            ( !File.Exists( path ) )             {

              this.Error( \"指定附件没有找到\"+path );             }

            {

              //得到附件字节流

              FileInfo file= FileInfo( path );

              FileStream fs= FileStream( path,FileMode.Open,FileAccess.Read );               ( fs.Length>( long )               .MaxValue )               {

                this.Error( \"附件大小超出了最大\" );               }

               file_b= [(                )fs.Length];

              fs.Read( file_b,0,file_b.Length );               fs.Close( );

               attatchmentMailStr=\"Content-Type:application/octet-stream;               \"+CRLF+\" \".PadRight( 8,' ' )+\"name=\"+               \"\"\"+file.Name+\"\"\"+CRLF;

              attatchmentMailStr\"Content-Transfer-Encoding:base\"+CRLF;               attatchmentMailStr\"Content-Disposition:attachment;               \"+CRLF+\" \".PadRight( 8,' ' )+\"filename=\"+               \"\"\"+file.Name+\"\"\"+CRLF+CRLF;

              attatchmentMailStrConvert.ToBaseString( file_b,0,file_b.Length)+CRLF+CRLF;

              attatchmentDatas.Add( attatchmentMailStr );             }           }

          //设置邮件信息

          ( mail.MailTypeMailTypes.Text ) //文本格式

          {

            message\"Content-Type:multipart/mixed;

            \"+CRLF+\" \".PadRight( 8,' ' )+\"boundary=\"=001_Dragon320037612222_=\"\"             +CRLF+CRLF;

            message\"This is a multi-part message in MIME format.\"+CRLF+CRLF;             message\"--=001_Dragon320037612222_=\"+CRLF;             message\"Content-Type:text/plain;             \"+CRLF+\" \".PadRight( 8,' ' )+\"

            char=\"\"+mail.MailEncoding.( ).ToLower( )+\"\"\"+CRLF;

            message\"Content-Transfer-Encoding:base\"+CRLF+CRLF;             ( mail.MailBody!=null )

            messageConvert.ToBaseString( mail.MailBody,0,mail.MailBody.Length)+CRLF;

            foreach(

             s in attatchmentDatas )             {

              message\"--=001_Dragon320037612222_=\"+CRLF+s+CRLF+CRLF;             }

            message\"--=001_Dragon320037612222_=--\"+CRLF+CRLF+CRLF+\".\"+CRLF;           }

          {

            message\"Content-Type:multipart/mixed;

            \"+CRLF+\" \".PadRight( 8,' ' )+\"boundary=\"=001_Dragon2555116284_=\"\"             +CRLF+CRLF;

            message\"This is a multi-part message in MIME format.\"+CRLF+CRLF;             message\"--=001_Dragon2555116284_=\"+CRLF;             message\"Content-Type:text/html;             \"+CRLF+\" \".PadRight( 8,' ' )+\"

            char=\"\"+mail.MailEncoding.( ).ToLower( )+\"\"\"+CRLF;

            message\"Content-Transfer-Encoding:base\"+CRLF+CRLF;             ( mail.MailBody!=null )

            messageConvert.ToBaseString( mail.MailBody,0,mail.MailBody.Length)+CRLF+CRLF;

            for(              i=0;

            i              message\"--=001_Dragon2555116284_=\"+CRLF+attatchmentDatas[i]+CRLF+CRLF;             }

            message\"--=001_Dragon2555116284_=--\"+CRLF+CRLF+CRLF+\".\"+CRLF;           }         }

        //发送邮件数据

        this.mailEncodingName=mail.MailEncoding.( );

        this.sendCommand( message,true );         (

        this.sendIsComplete )

        this.sendCommand( \"QUIT\      }

      catch       {

        isSended=false;       }

      finally       {

        this.disconnect( );         //输出日志文件         (

        this.LogPath!=null )         {

          FileStream fs=null;           ( File.Exists(           this.LogPath ) )           {

            fs= FileStream(

            this.LogPath,FileMode.Append,FileAccess.Write );

            this.logs=CRLF+CRLF+

            this.logs;           }

          fs= FileStream(

          this.LogPath,FileMode.Create,FileAccess.Write );

           logPath_b=Encoding.GetEncoding( \"gb2312\" ).GetBytes(           this.logs );

          fs.Write( logPath_b,0,logPath_b.Length );           fs.Close( );         }       }

       isSended;     }

    ///

      /// 异步写入数据      ///  

    ///  

    private void asyncCallBack( IAsyncResult result )      {

      ( result.IsCompleted )

      this.sendIsComplete=true;     }

    ///

      /// 关闭连接      ///

    private void disconnect( )      {

      try       {

        ns.Close( );         tc.Close( );       }

      catch       {

        ;       }     }

    ///

      /// 设置出现时动作      ///  

    ///       private void Error(      errorStr )      {

      this.errorMessage=errorStr;       logs

      this.errorMessage+CRLF+\"【邮件处理动作中止】\"+CRLF;

      this.disconnect( );

      throw ApplicationException( \"\" );     }

    ///

 

    ///将串转换为base      ///

 

    ///  

    ///       ///       private

     convertBaseString(      str,

     encodingName )      {

       str_b=Encoding.GetEncoding( encodingName ).GetBytes( str );        Convert.ToBaseString( str_b,0,str_b.Length );     }

    #endregion   } }

2009-1-9 12:47:24

疯狂代码 http://CrazyCoder.cn/

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- oldu.cn 版权所有 浙ICP备2024123271号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务