This is for
Email Send System (C # Based on SMTP Certification) 1.0 revision This first version is written in November 2002, after a year and a half, some people have mentioned opinions, and fix it, because the projects have been used No, I didn't pay attention.
Some time ago, some netizens fed back to some problems, this time I have made some corrections.
1, the message of the 163 in Text mode is not seen 2, if you receive the mail with Outlook instead of watching the email online, you will find the text content, but then follow some garbled .3, some newly opened mailbox received Garbled, such as *@126.com4, fix the mail with attachment, open an attachment, content chaos
Thanks Lion Interactive Network Forum SMHY8187 and mailboxes are friends on grassdragon_china@yahoo.com.cn.
You are welcome to make amendments, [Note:] It is best to give me a revised manus Mail, we work together to learn my email: lion-a@sohu.com lion.net@163.com
------------------------------------------
Source code download: Click to download
The following is the program source code:
Using system; using system.net; using system.net.sockets; using system.collections;
Namespace lion.Web.mail {/ * create by lion 2004-04-23 19:00 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 * / #Region ASPNETPAGER SERVER CONTROL
/// // / message can be transmitted /// summary> public class smtpmail {via SMTP mail service or any SMTP server built in Microsoft Windows 2000.
Private string enter = "/ r / n";
/// /// Setting the language code, the default setting is GB2312, if it is not required to be set to "" /// summary> private string _charset = "GB2312";
/// /// sender address /// summary> private string _from = ""
/// /// sender name /// summary> private string _fromname = ""
/// /// Reply email address /// summary> /// public string replyto = ""; /// /// recipient name /// summary> private String_RecipientName = ""
/// /// Recipient list /// summary> private haShtable recipient = new hashtable ();
/// /// mail server domain name /// summary> private string mailserver = "
/// /// Mail server port number /// summary> private int mailserverport = 25;
/// /// SMTP authentication User Name /// summary> private string username = "";
/// /// SMTP authentication password /// summary> private string password = "";
/// //: Do not need SMTP verification /// summary> private bool esmtp = false;
/// /// is HTML mail /// summary> private bool _html = false;
/// /// Email attachment list /// summary> private ilist attachments;
/// /// message Send priority, can be set to "High", "Normal", "Low" or "1", "3", "5" /// summary> Private String Priority = "Normal";
/// /// mail topic /// summary> private string _subject;
/// /// message body /// summary> private string _body; /// /// secret recipient list /// summary> /// private hashTable RecipientBCC = new hashtable ();
/// /// Repair number /// summary> private int RecipientNum = 0;
/// /// Up to the number of recipients /// summary> private INT RecipientMaxNum = 5;
/// /// Distinguisher number /// summary> /// private int RecipientBccnum = 0;
/// /// error message feedback /// summary> private string errmsg; /// /// TCPClient object for connection server /// summary> private tclient tc;
/// ///// summary> private networkStream ns; /// /// server interactive record /// summary> private string logs = "
/// /// SMTP error code hash table /// summary> private hashtable errcodeht = new hashtable ();
/// /// SMTP correct code hash table /// summary> private hashtable rightcodeht = new hashtable ();
/// /// Initialization new instance ///// / summary> public smtpmail () {attachments = new system.collections.arrayList ( }
#Region Properties
/// /// mail topic /// summary> public string subject {get {return this._subject;} set {THIS._SUBJECT = VALUE;}}
/// /// message body /// summary> public string body {get {return this._body;} set {THIS._BODY = value;}}
/// /// sender address /// summary> public string from {get {return_from;} set {this._from = value;}}
/// /// Setting the language code, the default setting is GB2312, if you do not need to be set to "" /// summary> public string charset {get {returnim "}}} set {THIS ._charset = value;}}
/// /// sender name ////// summary> public string fromname {get {return this._fromname;} set {this._fromname = value;}}
/// /// Recipient Name /// summary> public string recipientname {get {return this._recipientname;} set {this._recipientname = value;}} /// // / Mail Server Domain Name and Verification Information /// Shape As: "User: Pass@www.server.com: 25", you can also save 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
(":") - 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 = ""; esmtp = false;}}}
//////////////////////////////////////////////////////////////////////////////// /// Mail Send Priority, you can set To "High", "Normal", "Low" or "1", "3", "5" /// summary> public string priority {set {switch (value.tolower ()) {copy "high" : Priority = "hor";
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;}}}
/// /// is HTML mail /// summary> public bool html {get {returnim {this._html = value;}}
/// /// error message feedback /// summary> public string errorMessage {get {return errmsg;}}
/// /// server interacts, if found that the SMTP server that this component cannot be used, please send me the logs when the error (lion-a@sohu.com), I will find it as soon as possible
the reason. /// summary> public string logs {get {return logs;}}
/// /// Most recipients /// summary> public int RecipientMaxnum {set {recipientmaxnum = value;}}
#ndregion
#Region Methods
/// /// Add mail attachment /// summary> /// attachment absolute path param> public void addattachment (params string [] filepath) {ix ( FilePath == NULL) {Throw ("FilePath"));} for (int i = 0; i // / Add a set of recipients (not more than RecipientMaxNum), parameter is a string array /// summary> /// Save a string with the recipient address array (not more than recipientmaxnum a) param> public bool AddRecipient (params string [] Recipients) {if (Recipient == null) {Dispose (); throw (new ArgumentNullException ( "Recipients"));} for (int i = 0; I /// Send an email method, all parameters are set by attribute. /// summary> public bool send () {if (mailserver.trim () == "" {throw ("Recipient", "must specify SMTP server"));
Return sendemail ();
/// /// Send email method /// summary> ///
Interest, such as "www.smtpserver.com" param> public bool send (string smtpserver) {maildomain = SMTPSERVER; RETURN Send ();} /// /// Send Mail Method /// summary > /// SMTP server information, such as "UserName: Password@www.smtpserver.com: 25", you can also remove some times
Interest, such as "www.smtpserver.com" param> /// sender Mail address param> /// sender name < / param> /// Recipient address param> /// Referth param> /// Whether html mail param> /// Mail topic param> /// mail body param> public bool send (String SMTPServer, String from, String fromname, String to, String Toname, Bool HTML, STRING
subject, string body) {MailDomain = smtpserver; From = from; FromName = fromname; AddRecipient (to); RecipientName = toname; Html = html; Subject = subject; Body = body; return Send ();}
#ndregion
#Region Private Helper Functions
/// /// Add a recipient /// summary> /// Recipient Address param> Private Bool AddRecipient (String Recipients) {IF RecipientNum
"));}}
Void Dispose () {if (ns! = null) ns.close (); if (tc! = null) tc.close ();} /// /// SMTP response code hash table /// summary> privated () {errcodeht.add ("500", "mailbox address error"); errcodeht.add ("501", "Parameter Format Error"); errcodeht.add ("502", "command Not implemented "); errcodeht.add (" 503 "," Server requires SMTP verification "); errcodeht.add (" 504 "," command parameter is not implemented "); errcodeht.add (" 421 "," service is not ready, Turning off the transport channel "); errcodeht.add (" 450 ", the email operation required by the requirements is not completed, the mailbox is unavailable (for example, mailbox busy)"); errcodeht.add ("550", "The mail operation is not completed, The mailbox is unavailable (for example, mailbox is not found, or is not accessible) "); errcodeht.add (" 451 "," abandon the requirements of the required operation; error during processing "); errcodeht.add (" 551 "," User non-local , Please try "); errcodeht.add (" 452 "," system storage is insufficient, the required operation is not executed "); errcodeht.add (" 552 "," excess storage allocation, required operation Execute "); errcodeht.add (" 553 "," mailbox name is unavailable, the required operation is not executed (such as mailbox format error) "); errcodeht.add (" 432 "," requires a password conversion "); errcodeht. Add ("534", "authentication mechanism is too simple"); errcodeht.add ("538", "Current Request Certification Mechanism Requires"); Errcodeht.Add ("454", "Temporary Certification"); errcodeht. Add ("530", "requires authentication");
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 to encode param> Private String Base64Encode ) {Byte [] barray; barray = encoding.default.getBytes (str); return convert.tobase64string (barray);} /// /// Decoding the base64 string is normal string /// Summary> /// String param> private string base64decode (string str) {byte [] barray; barray = convecture.default.getstring (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));}
/// /// Send SMTP command /// summary> private bool sendcommand (string str) {byte [] WriteBuffer; if (str == null || str.trim () == String.empty ) {RETURN TRUE;} logs = Str; WriteBuffer = Encoding.default.getbytes (STR); try {ns.write (WriteBuffer, 0, WriteBuffer.Length);} catch {errmsg = "Network connection error"; RETURN FALSE; } Return True;}
/// /// Receive SMTP server response /// summary> private string recnse () {int streemsize; string returnvalue = string.empty; 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 this.enter; 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;} /// /// sendemail /// ////// returns> 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 " enter;
} IF (! Dialog (SendBuffer, "Incomplete")) Return False;
/ * Sendbuffer = new string [10]; for (int i = 0; i
SendBuffer [I] = "RCPT TO: <" RecipientBCC [i] .tostring () "> ENTER;
}
If (! Dialog (SendBuffer, "PassBuffer")) Return False; * / sendbufferstr = "Data" Enter; if (! Dialog (sendbufferstr, ")) Return False; sendbufferstr =" from: " Fromname " <" from "> enter;
//if(ReplyTo.trim () != "" // {// sendbufferstr = "reply-to:" replyto enter; //}
// sendbufferstr = "TO:" RecipientName "<" Recipient [0] " Enter; sendbuffrstr =" to: =? " CHARSET.TOUPPER () " B? " Base64Encode RecipientName) "? =" "<" Recipient [0]
">" ENTER; SendBufferstr = "CC:"; for (int i = 0; i "; seundbufferstr = Enter;
SendBufferstr = ((Subject == String.empty || Subject == NULL)? "Subject:": ((Charset == ")? (" Subject: "
Subject) :( "Subject:" "=?" "? B?" Base64encode (subject) "? ="))) Enter; sendbufferstr = "x-priority:" priority enter; SendBufferstr = "X-MSMail-priority:" priority enter; SendBufferstr = "Importance:" priority enter; SendBufferstr = "X-Mailer: Lion.Web.Mail.SmtpMail Pubclass [cn]" Enter; sendbufferstr = "mime-version: 1.0" enter; if (attachments.count! = 0) {sendBufferstr = "content-type: multipart / mix;" Enter; sendbufferstr = "boundary = /" === == " (html?" 001_dragon520636771063 _ ":" 001_dragon303406132050 _ ") " ===== / "" ENTER ENTER;
IF (html) {if (attachments.count == 0) {sendbufferstr = "Content-type: multipart / alternative;" Enter; // Content format and separator sendbufferstr = "boundary = /" ==== = 003_Dragon520636771063 _ ===== / "" ENTER ENTER;
SendBufferstr = "this is a multi-part message in mime format." ENTER ENTER;} else {sendbufferstr = "this is a multi-part message in mime format." ENTER ENTER; SendBufferstr = "- - ===== 001_dragon520636771063 _ ===== " enter; sendbufferstr =" content-type: multipart / alternative; " enter; // content format and separator sendbufferstr =" boundary = / "=== == 003_Dragon520636771063 _ ===== / "" Enter Enter;} sendbufferstr = "- ===== 003_Dragon520636771063 _ =====" Enter; sendbufferstr = "Content-Type: text / plain; " Enter; SendBufferstr = ((Charset ==")? ("Charset = /" ISO-8859-1 / "): (" charset = / ""
Charset.tolower () "/" ")) Enter; sendbufferstr =" content-transfer-encoding: base64 " ENTER ENTER; sendbufferstr = base64encode (" mail content is HTML format, select HTML mode ") ENTER ENTER;
SendBufferstr = "- ===== 003_dragon520636771063 _ =====" ENTER;
SendBufferstr = "Content-Type: Text / HTML;" Enter; SendBufferstr = ("Charset = /" ISO-8859-1 / "): (" charset = / "
Charset.tolower () "/" ")) Enter; sendbufferstr =" Content-Transfer-Encoding: Base64 " ENTER ENTER; SendBufferstr = Base64Encode (body) ENTER ENTER; SendBufferstr =" - == === 003_dragon520636771063 _ ===== - " ENTER;} else {if (attachments.count! = 0) {sendbufferstr =" - ===== 001_dragon303406132050 _ ===== " ENTER;} SendBufferstr = "Content-Type: Text / Plain;" Enter; SendBufferstr = ("CharSet = /" ISO-8859-1 / "): (" charset = / " Charset.ToLower () "/" ")) enter; SendBufferstr =" Content-Transfer-Encoding: base64 " enter enter; SendBufferstr = Base64Encode (Body) enter;} // SendBufferstr =" Content-Transfer -ENCODING: BASE64 " ENTER;
IF (attachments.count! = 0) {for (int i = 0; i
(? Html "001_Dragon520636771063 _": "001_Dragon303406132050_") "=====" enter; // SendBufferstr = "Content-Type: application / octet-stream" enter; SendBufferstr = "Content-Type: text / plain; enter; sendbufferstr = "name = /" =? " charset.toupper () "? b? " Base64Encode
(filepath.substring ("//") 1)) "? = /" " Enter; sendbufferstr =" Content-Transfer-Encoding: Base64 " ENTER; SendBufferstr =" Content-Disposition : attachment; " Enter; sendbufferstr =" filename = / "=?" charset.toupper () "? b?" base64encode (filepath.substring (filepath.lastIndexof ("//") 1)) "? = /" Enter Enter; sendbufferstr = getStream (filepath) ENTER ENTER;} SendBufferstr = "- =====" (HTML? "001_dragon520636771063 _": "001_dragon303406132050_")
"===== -" Enter Enter;} SendBufferstr = 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;
#ndregion
#REGON / * /// /// Add a Dissipner /// summary> /// Recipient address param> public bool addrecipientbcc (String str) {if (str == null || str.Trim () == "") return true; if (RecipientBCCNum <10) {RecipientBCC.Add (RecipientBCCNum, str); RecipientBCCNum ; return true;} else {errmsg = "Too much recipient"; return false;}}
/// // / Add a set of portable recipients (no more than 10), parameter is a string number / /// summary> /// Save a receipt Human address string array (no more than 10) param> public bool addrecipientbcc (string [] str) {for (int i = 0; i
#ndregion}