专注于互联网--专注于架构

最新标签
网站地图
文章索引
Rss订阅

首页 »DotNet » smtp邮件服务器:用c#写的smtp邮件发送类(2) »正文

smtp邮件服务器:用c#写的smtp邮件发送类(2)

来源: 发布时间:星期五, 2009年1月9日 浏览:14次 评论:0

    
    /// <summary> 
    /// 向SMTP发送命令 
    /// </summary> 
    /// <param name="cmd"></param> 
    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;
      }
    }
    
    /// <summary> 
    /// 通过auth login方式登陆smtp服务器 
    /// </summary> 
    private void landingByLogin( ) 
    {
       base64UserId=
      this.convertBase64String(
      this.UserID,"ASCII" );
      
       base64Pass=
      this.convertBase64String(
      this.Password,"ASCII" );
      //握手
      this.sendCommand( "helo "+
      this.serverName,false );
      //开始登陆
      this.sendCommand( "auth login",false );
      
      this.sendCommand( base64UserId,false );
      
      this.sendCommand( base64Pass,false );
    }
    
    /// <summary> 
    /// 通过auth plain方式登陆服务器 
    /// </summary> 
    private void landingByPlain( ) 
    {
       NULL=( (
      char )0 ).( );
      
       loginStr=NULL+
      this.UserID+NULL+
      this.Password;
      
       base64LoginStr=
      this.convertBase64String( loginStr,"ASCII" );
      //握手
      this.sendCommand( "helo "+
      this.serverName,false );
      //登陆
      this.sendCommand( base64LoginStr,false );
    }
    
    /// <summary> 
    /// 通过auth CRAM-MD5方式登陆 
    /// </summary> 
    private void landingByCRAMMD5( ) 
    {
      //握手
      this.sendCommand( "helo "+
      this.serverName,false );
      //登陆
       response=
      this.sendCommand( "auth CRAM-MD5",false );
      //得到服务器返回标识
       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 );
    }
    
    /// <summary> 
    /// 发送邮件 
    /// </summary> 
    /// <s></s> 
    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+">",false );
        //标识收件人( 对应SMTP命令Rcpt )
        foreach(
         receive in mail.Receivers )
        {
          this.sendCommand( "rcpt to:<"+receive+">",false );
        }
        //标识开始输入邮件内容( Data )
        this.sendCommand( "data",false );
        //开始编写邮件内容
         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:base64"+CRLF+CRLF;
            ( mail.MailBody!=null )
            messageConvert.ToBase64String( 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:base64"+CRLF+CRLF;
            ( mail.MailBody!=null )
            messageConvert.ToBase64String( 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:base64"+CRLF;
              attatchmentMailStr"Content-Disposition:attachment;
              "+CRLF+" ".PadRight( 8,' ' )+"filename="+
              """+file.Name+"""+CRLF+CRLF;
              attatchmentMailStrConvert.ToBase64String( 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:base64"+CRLF+CRLF;
            ( mail.MailBody!=null )
            messageConvert.ToBase64String( 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_Dragon255511664284_=""
            +CRLF+CRLF;
            message"This is a multi-part message in MIME format."+CRLF+CRLF;
            message"--=001_Dragon255511664284_="+CRLF;
            message"Content-Type:text/html;
            "+CRLF+" ".PadRight( 8,' ' )+"
            char=""+mail.MailEncoding.( ).ToLower( )+"""+CRLF;
            message"Content-Transfer-Encoding:base64"+CRLF+CRLF;
            ( mail.MailBody!=null )
            messageConvert.ToBase64String( mail.MailBody,0,mail.MailBody.Length )+CRLF+CRLF;
            for(
             i=0;
            i<attatchmentDatas.Count;
            i )
            {
              message"--=001_Dragon255511664284_="+CRLF+attatchmentDatas[i]+CRLF+CRLF;
            }
            message"--=001_Dragon255511664284_=--"+CRLF+CRLF+CRLF+"."+CRLF;
          }
        }
        //发送邮件数据
        this.mailEncodingName=mail.MailEncoding.( );
        
        this.sendCommand( message,true );
        (
        this.sendIsComplete )
        this.sendCommand( "QUIT",false );
      }
      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;
    }
    
    /// <summary> 
    /// 异步写入数据 
    /// </summary> 
    /// <param name="result"></param> 
    private void asyncCallBack( IAsyncResult result ) 
    {
      ( result.IsCompleted )
      this.sendIsComplete=true;
    }
    
    /// <summary> 
    /// 关闭连接 
    /// </summary>
    private void disconnect( ) 
    {
      try
      {
        ns.Close( );
        tc.Close( );
      }
      catch
      {
        ;
      }
    }
    
    /// <summary> 
    /// 设置出现动作 
    /// </summary> 
    /// <param name="errorStr"></param> 
    private void Error(
     errorStr ) 
    {
      this.errorMessage=errorStr;
      logs
      this.errorMessage+CRLF+"【邮件处理动作中止】"+CRLF;
      
      this.disconnect( );
      throw ApplicationException( "" );
    }
    
    /// <summary> 
    ///将串转换为base64 
    /// </summary> 
    /// <param name="str"></param> 
    /// <param name="encodingName"></param> 
    /// <s></s> 
    private
     convertBase64String(
     str,
     encodingName ) 
    {
       str_b=Encoding.GetEncoding( encodingName ).GetBytes( str );
       Convert.ToBase64String( str_b,0,str_b.Length );
    }
    #endregion
  }
}


0

相关文章

读者评论

发表评论

  • 昵称:
  • 内容: