熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

支持ESMTP身份驗證的郵件發送

2022-06-13   來源: .NET編程 

  使用NET Framework下的SystemNetMailSmtpClient可以很容易的實現郵件發送但現在很多郵件服務器已經支持ESMTP協議而ESMTP最大的區別在於發送時需要提供帳號密碼做驗證ESMTP通過流的方式發送命令與服務器交互完成郵件的發送與接受更多關於SMTP的命令請參考<>

  下面是一個簡單的示例(沒有做任何判斷與封裝僅供參考)

  代碼

  string smtp = ;

  string from = ;

  string pwd = pwd;

  string to = ;

  //建立鏈接

  TcpClient tc = new TcpClient(smtp);

  byte[] b = new byte[];

  tcGetStream()Read(bbLength);

  ResponseWrite(EncodingUTFGetString(b)+<br/>);

  //標識身份

  WriteMsg(tcGetStream() HELO xxxx\r\n);

  ResponseWrite(ReadMsg(tcGetStream()) + <br/>);

  //身份驗證開始

  WriteMsg(tcGetStream() AUTH LOGIN\r\n);

  ResponseWrite(ReadMsg(tcGetStream()) + <br/>);

  //帳號 base編碼

  byte[] bTxt=new byte[];

  bTxt=EncodingUTFGetBytes(from);

  WriteMsg(tcGetStream() ConvertToBaseString(bTxt)+\r\n);

  ResponseWrite(ReadMsg(tcGetStream()) + <br/>);

  //密碼base編碼

  bTxt=EncodingUTFGetBytes(pwd);

  WriteMsg(tcGetStream() ConvertToBaseString(bTxt) + \r\n);

  ResponseWrite(ReadMsg(tcGetStream()) + <br/>);

  //身份驗證結束

  //發送郵件地址

  WriteMsg(tcGetStream() stringFormat(MAIL FROM:{}\r\n from));

  ResponseWrite(ReadMsg(tcGetStream()) + <br/>);

  //接受郵件地址可以有多個RCPT TO

  WriteMsg(tcGetStream() stringFormat(RCPT TO:{}\r\n to));

  ResponseWrite(ReadMsg(tcGetStream()) + <br/>);

  //初如化

  WriteMsg(tcGetStream() DATA \r\n);

  ResponseWrite(ReadMsg(tcGetStream()) + <br/>);

  //郵件內容

  StringBuilder sb = new StringBuilder();

  sbAppendFormat(From:{}\r\n from);//發信人

  sbAppendFormat(To:{}\r\n to);//收信人可以有多個用分號隔開 這兩行可以與上面的MAIL FROM和RCPT TO不同(顯示在郵件內容裡的)

  sbAppendFormat(Date:{}\r\nDateTimeNowToString());//時間

  sbAppendFormat(Subject:{}\r\n 測試);//主題

  sbAppend(\r\n);

  sbAppend(內容); //正文

  sbAppend(\r\n\r\n);

  WriteMsg(tcGetStream() sbToString());

  ResponseWrite(ReadMsg(tcGetStream()) + <br/>);

  //結束會話

  WriteMsg(tcGetStream() QUIT);

  //關閉鏈接

  tcClose();

  如果運行正常上面的返回狀態依次為

   ESMTP CMailServer SMTP Service Ready

   welcome here

   VXNlcmhbWU

   UGFzcdvcmQ

   OK

   OK

   OK

   send the mail data end with

   OK


From:http://tw.wingwit.com/Article/program/net/201311/13700.html
  • 上一篇文章:

  • 下一篇文章:
  • 推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.