⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 smtpclass.cs

📁 smtp收邮件
💻 CS
📖 第 1 页 / 共 2 页
字号:
    //检查状态码
    string statusCode=response.Substring(0,3);
    bool isExist=false;
    bool isRightCode=true;
    foreach(string err in this.errorCodes.Keys)
    {
     if(statusCode==err)
     {
      isExist=true;
      isRightCode=false;
      break;
     }
    }
    foreach(string right in this.rightCodes.Keys)
    {
     if(statusCode==right)
     {
      isExist=true;
      break;
     }
    }
    //根据状态码来处理下一步的动作
    if(!isExist) //不是合法的SMTP主机
    {
     this.setError("不是合法的SMTP主机,或服务器拒绝服务");
    }
    else if(!isRightCode)//命令没能成功执行
    {
     this.setError(statusCode+":"+this.errorCodes[statusCode]);
    }
    else //命令成功执行
    {
     this.errorMessage="";
    }
    return response;
   }
   else
   {
    return null;
   }
  }
  /// <summary>
  /// 通过auth login方式登陆smtp服务器
  /// </summary>
  private void landingByLogin()
  {
   string base64UserId=this.convertBase64String(this.UserID,"ASCII");
   string 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()
  {
   string NULL=((char)0).ToString();
   string loginStr=NULL+this.UserID+NULL+this.Password;
   string 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);
  // //登陆
  // string response=this.sendCommand("auth CRAM-MD5",false);
  // //得到服务器返回的标识
  // string identifier=response.Remove(0,4);
  // //用MD5加密标识
  // KSN_MACTripleDES mac=new KSN_MACTripleDES();
  // mac.Key=this.Password;
  // mac.Data=Encoding.ASCII.GetBytes(identifier);
  // string hash=mac.GetHashValue();
  // //发送用户帐号信息
  // this.sendCommand(this.UserID+" "+hash,false);
  //}
  /// <summary>
  /// 发送邮件
  /// </summary>
  /// <returns></returns>
  public bool SendMail(MailMessage mail)
  {
   bool isSended=true;
   try
   {
    //检测发送邮件的必要条件
    if(mail.Sender==null)
    {
     this.setError("没有设置发信人");
    }
    if(mail.Receivers.Count==0)
    {
     this.setError("至少要有一个收件人");
    }
    if(this.SmtpValidateType!=SmtpValidateTypes.None)
    {
     if(this.userid==null || this.password==null)
     {
      this.setError("当前设置需要smtp验证,但是没有给出登陆帐号");
     }
    }
    //开始登陆
    switch(this.SmtpValidateType)
    {
     case SmtpValidateTypes.None:
      this.sendCommand("helo "+this.serverName,false);
      break;
     case SmtpValidateTypes.Login:
      this.landingByLogin();
      break;
     case SmtpValidateTypes.Plain:
      this.landingByPlain();
      break;
     //case SmtpValidateTypes.CRAMMD5:
     // this.landingByCRAMMD5();
     // break;
     default:
      break;
    }
    //初始化邮件会话(对应SMTP命令mail)
    this.sendCommand("mail from:<"+mail.Sender+">",false);
    //标识收件人(对应SMTP命令Rcpt)
    foreach(string receive in mail.Receivers)
    {
     this.sendCommand("rcpt to:<"+receive+">",false);
    }
    //标识开始输入邮件内容(Data)
    this.sendCommand("data",false);
    //开始编写邮件内容
    string message="Subject:"+mail.Subject+CRLF;
    message+="X-mailer:"+mail.XMailer+CRLF;
    message+="MIME-Version:1.0"+CRLF;
    if(mail.Attachments.Count==0)//没有附件
    {
     if(mail.MailType==MailTypes.Text) //文本格式
     {
      message+="Content-Type:text/plain;"+CRLF+" ".PadRight(8,' ')+"charset=\""+
       mail.MailEncoding.ToString()+"\""+CRLF;
      message+="Content-Transfer-Encoding:base64"+CRLF+CRLF;
      if(mail.MailBody!=null)
       message+=Convert.ToBase64String(mail.MailBody,0,mail.MailBody.Length)+CRLF+CRLF+CRLF+"."+CRLF;
     }
     else//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,' ')+"charset=\""+
       mail.MailEncoding.ToString().ToLower()+"\""+CRLF;
      message+="Content-Transfer-Encoding:base64"+CRLF+CRLF;
      if(mail.MailBody!=null)
       message+=Convert.ToBase64String(mail.MailBody,0,mail.MailBody.Length)+CRLF+CRLF;
      message+="--=====003_Dragon310083331177_=====--"+CRLF+CRLF+CRLF+"."+CRLF;
     }
    }
    else//有附件
    {
     //处理要在邮件中显示的每个附件的数据
     //   System.Collections.Specialized.StringDictionary attatchmentDatas = new System.Collections.Specialized.StringDictionary();
     //foreach(string path in mail.Attachments)
     //{
     // if(!File.Exists(path))
     // {
     //  this.setError("指定的附件没有找到"+path);
     // }
     // else
     // {
     //  //得到附件的字节流
     //  FileInfo file=new FileInfo(path);
     //  FileStream fs=new FileStream(path,FileMode.Open,FileAccess.Read);
     //  if(fs.Length>(long)int.MaxValue)
     //  {
     //   this.setError("附件的大小超出了最大限制");
     //  }
     //  byte[] file_b=new byte[(int)fs.Length];
     //  fs.Read(file_b,0,file_b.Length);
     //  fs.Close();
     //  string 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;
     //  attatchmentMailStr+=Convert.ToBase64String(file_b,0,file_b.Length)+CRLF+CRLF;
     //  attatchmentDatas.Add(attatchmentMailStr);
     // }
     //}
     ////设置邮件信息
     //if(mail.MailType==MailTypes.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,' ')+"charset=\""+mail.MailEncoding.ToString().ToLower()+"\""+CRLF;
     // message+="Content-Transfer-Encoding:base64"+CRLF+CRLF;
     // if(mail.MailBody!=null)
     //  message+=Convert.ToBase64String(mail.MailBody,0,mail.MailBody.Length)+CRLF;
     // foreach(string s in attatchmentDatas)
     // {
     //  message+="--=====001_Dragon320037612222_====="+CRLF+s+CRLF+CRLF;
     // }
     // message+="--=====001_Dragon320037612222_=====--"+CRLF+CRLF+CRLF+"."+CRLF;
     //}
     //else
     //{
     // 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,' ')+"charset=\""+mail.MailEncoding.ToString().ToLower()+"\""+CRLF;
     // message+="Content-Transfer-Encoding:base64"+CRLF+CRLF;
     // if(mail.MailBody!=null)
     //  message+=Convert.ToBase64String(mail.MailBody,0,mail.MailBody.Length)+CRLF+CRLF;
     // for(int i=0;i<attatchmentDatas.Count;i++)
     // {
     //  message+="--=====001_Dragon255511664284_====="+CRLF+attatchmentDatas[i].ToString()+CRLF+CRLF;
     // }
     // message+="--=====001_Dragon255511664284_=====--"+CRLF+CRLF+CRLF+"."+CRLF;
     //}
    }
    //发送邮件数据
    this.mailEncodingName=mail.MailEncoding.ToString();
    this.sendCommand(message,true);
    if(this.sendIsComplete)
     this.sendCommand("QUIT",false);
   }
   catch
   {
    isSended=false;
   }
   finally
   {
    this.disconnect();
    //输出日志文件
    if(this.LogPath!=null)
    {
     FileStream fs=null;
     if(File.Exists(this.LogPath))
     {
      fs=new FileStream(this.LogPath,FileMode.Append,FileAccess.Write);
      this.logs=CRLF+CRLF+this.logs;
     }
     else
      fs=new FileStream(this.LogPath,FileMode.Create,FileAccess.Write);
     byte[] logPath_b=Encoding.GetEncoding("gb2312").GetBytes(this.logs);
     fs.Write(logPath_b,0,logPath_b.Length);
     fs.Close();
    }
   }
   return isSended;
  }
  /// <summary>
  /// 异步写入数据
  /// </summary>
  /// <param name="result"></param>
  private void asyncCallBack(IAsyncResult result)
  {
   if(result.IsCompleted)
    this.sendIsComplete=true;
  }
  /// <summary>
  /// 关闭连接
  /// </summary> 
  private void disconnect()
  {
   try
   {
    ns.Close();
    tc.Close();
   }
   catch
   {
    ;
   }
  }
  /// <summary>
  /// 设置出现错误时的动作
  /// </summary>
  /// <param name="errorStr"></param>
  private void setError(string errorStr)
  {
   this.errorMessage=errorStr;
   logs+=this.errorMessage+CRLF+"【邮件处理动作中止】"+CRLF;
   this.disconnect();
   throw new ApplicationException("");
  }
  /// <summary>
  ///将字符串转换为base64
  /// </summary>
  /// <param name="str"></param>
  /// <param name="encodingName"></param>
  /// <returns></returns>
  private string convertBase64String(string str,string encodingName)
  {
   byte[] str_b=Encoding.GetEncoding(encodingName).GetBytes(str);
   return Convert.ToBase64String(str_b,0,str_b.Length);
  }
  #endregion
 }
    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -