Using system; using system.net; using system.net.sockets; using system.collections;
Namespace lion_office.data.library.mailclass {/ * create by lion 2002-11-20 01:44 CopyRight (c) 2001,2002 www.lionsky.net. All rights reserved. Web: http://www.lionsky.net Email: lion-a@sohu.com support .NET Framework Beta 2 * / public class esmtpmail {private string enter = "/ r / n"; /// // / set language code, default setting to GB2312, if it is not necessary to be set to "" /// summary> public string charSet = "gb2312"; /// /// sender address /// summary> public string from = " "; /// /// sender name /// summary> public string fromname =" "; /// /// Reply email address /// summary> // Public string replyto = ""; /// /// Recipient name /// summary> public string recipientname = ""; /// /// recipient list /// summary> private = new hashtable (); /// /// mail server domain name /// summary> private string mailserver = ""; //// /// mail server port number /// summary> private int mailserverport = 25; /// /////////////////////////////////////////////////////////////>> Private String UserName = ""; /// /// SMTP authentication password /////mmary> private string password = ""; /// // / if SMTP verification /// Summary> private bool esmtp = false; /// / / / HTML mail /// summary>
Public Bool HTML = false; /// /// Email attachment list /// summary> private system.collections.arraylist attachments; /// /// mail send priority, can be set to "High", "Normal", "Low" or "1", "3", "5" /// summary> private string priority = "normal"; /// /// mail topic / // summary> public string subject = ""; /// /// mail body /// summary> public string body = ""; /// /// recipient Number //// / summary> private INT RecipientNum = 0; /// /// Most recipients /// summary> private int RecipientMaxNum = 1; /// ///// Double transfer number /// summary> // private INT RecipientBccnum = 0; /// /// error message feedback /// summary> private string errmsg; /// / // TcpClient object, used to connect server /// summary> private tclient tc; /// /// NetWorkStream object /// summary> Private netstream ns; /// /// SMTP error code hash table /// summary> private haShtable errcodeht = new hashtable (); /// // / smtp correct code hash table /// summary> private haShtable rightcodeht = new hashtable (); public esmtpmail () {attachments = new system.collections.arrayList ();} /// /// mail server domain name and verification information /// / Shaped like: "User: pass @
Www.server.com:25 ", you can also save the secondary information. Such as" User: pass@www.server.com "or" www.server.com "/// summary> public string maildomain {set {string Maidomain = value.trim (); int tempint; if (maidomain! = ") {tempint = maidomain.indexof (" @ "); if (Tempint! = - 1) {string str = maidomain.substring (0, Tempint ); Mailserverusername = str.substring (0, str .indexof (":"))); mailserverpassword = str.substring (str.indexof ("::") 1, str.length-str.indexof (":")-Str.Indexof (":") 1); maidomain = maidomain.substring (Tempint 1, Maidomain.Length-Tempint-1);}
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
}
}
}
/// /// Mail server port number /// summary> public int maildomainport {set {mailserverport = value;}}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////> {● = value = "") {username = value.trim (); Else {username = ""}}}} /// /// SMTP authentication password //////mary> public string mailserverpassword {set {Password = Value }}
/// /// mail Send priority, can be set to "High", "Normal", "Low" or "1", "3", "5" /// summary> public string priority {Set {switch (value.tolower ()) {copy "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;}}}
/// /// error message feedback /// summary> public string errorMessage {get {return errmsg;}} /// /// server interaction record /// summary> private String logs = "";
/// // / server interacts records, if found the SMTP server that this component cannot be used, please send me the logs when the error (lion-a@sohu.com), I will find out the reason as soon as possible. /// summary> public string logs {get {return logs;}}
/// /// SMTP response code hash table /// summary> private void smtpcodeadd () {Errcodeht.add ("500", "Email Address Error"); errcodeht.add ("501" , "Parameter Format Error"); errcodeht.add ("502", "command is not implemented"); errcodeht.add ("503", "Server requires SMTP verification"); errcodeht.add ("504", "command parameters Not achievable "); errcodeht.add (" 421 "," Service is not ready, shut down the channel "); errcodeht.add (" 450 ", the email operation requiring the mail operation is not completed, the mailbox is not available (for example, mailbox busy)" ); Errcodeht.add ("550", "requested by mail operations, mailboxes are unavailable (for example, mailboxes are not found, or irresisible)"); errcodeht.add ("451", "abandon the required operation; In the process, "); errcodeht.add (" 551 "," users are not local, please try "); errcodeht.add (" 452 "," system storage is insufficient, requiring operations "); Errcodeht.Add ("552", "excess storage allocation, required operation is not executed"); errcodeht.add ("553", "mailbox name is not available, the required operation is not executed (such as a mailbox format error)"); Errcodeht.Add ("432", "need a password conversion"); errcodeht.add ("534", "authentication mechanism is too simple"); errcodeht.add ("538", "Current Request Certification Mechanism Requires")) Errcodeht.Add ("454", "Temporary Certification Failure"); Errcodeht.Add ("530", "Requires Certification");
Rightcodeht.Add ("220", "Service Ready"); RightCodeht.Add ("250", "Required Mail Operation"); RightCodeht.Add ("251", "User Non-Local, will forward to "); RightCodeht.add (" 354 "," Start Entry Enter, "End" in . ); RightCodeht.Add ("221", "Service Close Transfer Channel"); RightCodeht.Add ( "334", "server response verification base64 string"); RightCodeht.add ("235", "Verification Success");} /// /// The string is encoded as Base64 string /// < / summary> /// String param> private string base64encode (string str) {byte [] barray; barray = encoding.default.getbytes; return control; Return Convert. Tobase64String (Barray);
/// /// Differently decodes the base64 string /// /// / summary> /// String param> private string base64decode (String) Str) {byte [] barray; barray = convert.FromBase64String (str); return eNCoding.default.getstring (barray);}
/// ///> File stream /// summary> /// Accessories's absolute path param> private string getStream (String FilePath) {/ / Establish file flow object system.io.filestream filestr = new system.io.filestream (filepath, system.io.filemode.open); Byte [] by = new byte [system.convert.toint32 (fileStr.Length)]; FILESTR.READ (By, 0, By.Length); filestr.close (); return (system.convert.tobase64string (by));}
/// /// Add email attachment /// summary> /// Accessories absolute path param> public void addattachment (string path) {attachments.add (Path) );} /// /// Add a recipient /// summary> /// recipient address param> public bool addrecipient (String STR) {Str.trim (); if (str == null || str .indexof ("@") == - 1) Return True; if (RecipientNum
/// /// Most recipients /// summary> public int RecipientMaxnum {set {recipientmaxnum = value;}}
/// /// Add a set of recipients (not more than RecipientMaxNum), parameter is a string number / /// summary> /// Save a recipient Address string array (not more than RecipientMaxNum) paramaxnum) param> public bool addrecipient (String [] str) {for (int i = 0; i
/// /// Send SMTP command /// summary> private bool sendcommand (string str) {byte [] WriteBuffer; if (str == null || Str.trim () == "") {RETURN TRUE;} logs = Str; WriteBuffer = Encoding.default.getbytes (STR); trybuffer, 0, writebuffer.Length);} catch {errmsg = "network connection error"; Return False; Return true;} /// /// Receive SMTP server response /// summary> prince recrvresponse () {int StreetSize; string returnvalue = "; byte [] readbuffer = new byte [1024]; Try {streamsize = ns.read (readbuffer, 0, readbuffer.Length);} catch {errmsg = "Network connection error"; return "false";
IF (streamsize == 0) {Return ReturnValue;} else {returnvalue = encoding.default.getstring (readbuffer) .substring (0, streamsize); logs = returnvalue; return returnvalue;}}
/// /// interacts with the server, send a command and receives the response. /// summary> /// A command to send param> /// If the error, the information you want to feedback param> private Bool Dialog (String Str, String Errstr) {if (Str == Null || Str.trim () == "" "{Return true;}} (sendcommand (STR)) {string rr = recvResponse (); if ( RR == "false") {return false;} string rrcode = r.substring (0, 3); if (rightcodeht [rcode]! = Null) {ket true;} else {if (errcodeht [rrcode]! = Null ) {Errmsg = (rrcode errcodeht [rrcode] .tostring ()); errmsg = Enter;} else {errmsg = rr;} errmsg = errstr; return false;}} else {return false; }
/// /// interacts with the server, sends a set of commands and receives the response. /// summary>
Private bool dialog (str, str, string errstr) {for (int i = 0; i
Return True;}
Private Bool Sendemail () {// Connection Network TRY {TC = New TcpClient (MailServer, MailServerport);} catch (exception e) {errmsg = e.tostring (); return false;} ns = tc.getStream (); SMTPCodeAdd ();
/ / Verify that the network connection is correct if (rightcodeht [recject "(). Substring (0, 3)] == null) {errmsg =" Network connection failed "; return false;}
String [] SendBuffer; String SendBuffersTr;
// Perform SMTP verification if (esmtp) {sendbuffer = new string [4]; sendbuffler [0] = "ehlo" mailserver enter; sendbuffer [1] = "auth login" enter; sendbuffer [2] = base64encode Username) Enter; SendBuffer [3] = base64encode (password) Enter; if (! Dialog (SendBuffer, "SMTP server verification failed, check the username and password.")) Return false;} else {sendbufferstr = "Helo" MailServer Enter; if (! Dialog (SendBufferstr, ")) Return False;}
// sendbufferstr = "Mail from: <" from "> Enter; if (! Dialog (sendbufferstr," sender address error, or no empty ")) Return False;
// sendbuffer = new string [RecipientMaxNum]; for (int i = 0; i
Sendbuffer [I] = "RCPT TO: <" Recipient [i] .tostring () "> Enter;
} IF (! Dialog (SendBuffer, "Incomplete")) Return False;
SendBufferstr = "Data" Enter; if (! Dialog (sendbufferstr, ")) Return False; sendbufferstr =" from: " " " " " "> enter;
SendBufferstr = "to: =?" "?" " " <" "? = " " " "? = "> Enter; sendbufferstr =" Cc: "; for (int i = 0; i , "; SendBufferstr = Enter;
IF (charset == ") {sendbufferstr =" Subject: " Subject Enter;} else {sendbufferstr =" Subject: " " =? " CHARSET.TOUPPER () "? b? " base64encode (Subject) ) "? =" enter;}
SendBufferstr = "X-Priority:" priority enter; SendBufferstr = "X-MSMail-Priority:" priority enter; SendBufferstr = "Importance:" priority enter; SendBufferstr = "X-Mailer: Huolx.Pubclass" Enter; sendbufferstr = "MIME-VERSION: 1.0" ENTER;
SendBufferstr = "Content-Type: multipart / mixed;" enter; // content format and delimiters SendBufferstr = "boundary = /" ---- = _ NextPart_000_00D6_01C29593.AAB31770 / "" enter; SendBufferstr = "- ----- = _ NextPart_000_00D6_01C29593.AAB31770 " enter; if (Html) {SendBufferstr =" Content-Type: text / html; " enter;} else {SendBufferstr =" Content-Type: text / plain; " enter }
IF (charset == ") {sendbufferstr =" charset = / "ISO-8859-1 /" " enter;} else {sendbufferstr =" charset = / " charset.tolower () " / "" ENTER;} // sendbufferstr = "Content-Transfer-Encoding: Base64" Enter;
SendBufferstr = "Content-Transfer-Encoding: Base64" ENTER ENTER;
SendBufferstr = Base64Encode (Body) enter; if (! Attachments.Count = 0) {foreach (string filepath in Attachments) {SendBufferstr = "------ = _ NextPart_000_00D6_01C29593.AAB31770" enter; SendBufferstr = "Content -Type: Application / OCTET-Stream " Enter; SendBufferstr =" Name = / "=?" CHARSET.TOUPPER () "? B?" Base64encode (filepath.substring (filepath.lastindexof ("//" ) 1)) "? = /" " Enter; sendbufferstr =" content-transfer-encoding: base64 " enter; sendbuffrstr =" content-disposition: attachment; " enter; sendbufferstr =" filename = /"=?" charset.toupper () "?b?" base64encode(filepath.substring("//") 1) "?=/"" enter enter; sendbufferstr = GetStream (FilePath) ENTER ENTER;}}}}}}}}}} ------ = _ nextpart_000_00d6_01c29593.aab31770 - " ENTER ENTER; SEN DBufferstr = Enter "." Enter; if (! Dialog (SendBufferstr, "Error Letter Information") Return False;
SendBufferstr = "quit" enter; if (! Dialog (SendBufferstr, "Disconnecting When Connection Error")) Return False;
ns.close (); tc.close (); return true;
/// /// Send an email method, all parameters are set by attribute. /// summary> public bool send () {if (Recipient.count == 0) {errmsg = "Recipient list can not be empty"; Return False;}} (mailserver.trim () == "" ) {Errmsg = "must specify SMTP server"; return false;}
Return sendemail ();
/// /// Send email method /// summary> /// public bool send (string smtpserver) {maildomain = SMTPSERVER; RETURN Send ();