Email Send System (C # Based on SMTP Authentication) simple. But later found that SMTPMail with .NET does not support SMTP certification, and many SMTP servers do not only need to log in to verification, but also verify Mail from (such as 263), if the username and the username used do not match, so Decided to write a Sendmail program with C #, which refers to the idea of Huolx, and take some advantages.
You are welcome to make amendments, [Note: Please keep copyright when publish] It is best to give me a revised Mail, we learn my email: lion-a@sohu.com lion.net@163.com Download: Download Download Demleases: Lion Interactive Network Technical Articles, each article has mail package sent to send this component source code: using system; using system.text; using system.io; useing 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, the default setting is GB2312, if you do not need to be set to "" /// summary> public string charSet = "GB2312"; /// /// sender address // / summary> public string from = ""; /// /// sender name /// summary> public string fromname = ""; /// /// Reply mail Address /// summary> // public string replyto = ""; /// /// recipient name /// Summary> Public String RecipientName = ""; /// /// Recipient list /// summary> private haShtable recipient = new hashtable (); /// /// mail server domain name /// summary = ""; /// /// mail server port number /// summary> private int mailserverport = 25; /// /// SMTP Username /// summary> private string usrname = ""
///////////////////////////// // / /// // / /// //// summary> privacy BOOL ESMTP = false; /// /// is HTML mail /// summary> public bool html = false; /// /// mail attachment list /// summary> private System.collections.Arraylist attachments; /// /// message Send priority, can be set to "High", "Normal", "Low" or "1", "3", "5" ////// summary> private string priority = "normal"; /// /// mail topic /// summary> public string subject = ""; /// /// message body //// / summary> public string body = ""; /// /// Recipient number /// summary> private int RecipientNum = 0; /// /// Up to Number of people /// summary> private int RecipientMaxNum = 1; /// /// Distinguine Recipient Number /// summary> // Private int Recientb CCNUM = 0; /// /// Error message feedback /// summary> private string errmsg; /// /// TCPClient object for connection server /// summary> Private TCPCLIENT TC; /// /// NetWorkStream Object /// summary> private networkStream 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 /// Shape: "User: Paswww.server.com: 25", you can also save secondary information.
Such as "User: paswww.server.com" www.server.com "/// summary> public string maidomain {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;}} /// /// User Name /// summary> public string mailserverusername {set {ix (value.trim ()! = "" {Username = value = "" {usrname = value;
} Else {username = ""; esmtp = false;}}}} /// /// /////////////////////////////> Summary> 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 ()) {case "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 errorMsG;} } /// /// server interaction record /// summary> private string logs = ""; ///
/// server interactive record, 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 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 are not implemented "); errcodeht.add (" 421 "," Service is not ready, shut down the transport channel "); errcodeht.add (" 450 ", "The required mail operation is not completed, the mailbox is unavailable (for example, mailbox busy)"); errcodeht.add ("550", the email operation requested by the mail is not completed, the mailbox is unavailable (for example, the mailbox is not found, or not accessible) "); Errcodeht.add (" 451 "," Abandon the requirements of the requirements; error during processing "); errcodeht.add (" 551 "," User is not local, please try "; errcodeht.add ("452", "system storage is insufficient, requiring operation"); errcodeht.add ("552", "excess storage allocation, required operation is not executed"); Errcodeht.Add ("553", "mailbox 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", "The currently requested certification mechanism needs to be encrypted") Errcodeht.Add ("454", "Temporary Certification Failure"); Errcodeht.Add ("530", "Requirements"); RightCodeht.Add ("220", "Service Ready"); RightCodeht.Add ("250 "," Required Mail Operation "); RightCodeht.Add (" 251 "," User is non-local, will forward to ");
Rightcodeht.add ("354", "Start Mail 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.Tobase64String (Barray); Return Convert.TOBASE64STRING (BARRY); } /// /// Differently decodes the base64 string /// //// To decode the string param> private string base64decode String str) {byte [] barray; barray = convert.frombase64string (str); return eNCoding.default.getstring (barray);} /// ///> File flow /// summary > /// The absolute path of the attachment param> private string getStream (String filepath) {// Establish a file stream object System.IO.FileStr Eam filestr = new system.io.filestream (filepath, system.io.filemode.open); byte [] by = new byte [system.convert.toint32; filestr.read (by, 0, by); FileStr.Read .LeSTR.Close (); return (system.convert.tobase64string (by));} /// /// Add mail attachment /// summary> /// Accessories Absolute Path param> public void addattachment (string path) {attachments.add (path);} /// <
Summary> /// Add a recipient /// summary> /// Recipient address param> public bool addrecipient (string str) {str.trim ( ); If (str == null || str .indexof ("@") == - 1) Return true; if (RecipientNum /// Up to the number of recipients ////////////////////> summary> Public int RecipientMaxNum {set {RecipientMaxNum = Value;}} /// /// Add a set of recipients (no more than RecipientMaxNum), parameter is a string number / // summary> /// Save strings (not more than RecipientMaxNum) paramaxnum) paramaxn {for (int i = 0; i /// Send SMTP command /// summary> prince bool sendcommand (string str) {byte [] WriteBuffer; if ( Str == null || str.trim () == "" "} logs = Str; writebuffler = encoding.default.getbytes (STR); try {ns.write (WriteBuffer, 0, WriteBuffer.Length) ;
} CatCH {errmsg = "Network connection error"; returnial;} /// /// receives SMTP server response //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////bit String Recvresponse () {int StreetSize; String ReturnValue = ""; Byte [] readbuffer = new byte [1024]; try {streamsize = ns.read (readbuffer, 0, readbuffer.Length);} catch {errmsg = "Network connection error";} if (streamSize == 0) {return returnvalue;} else {returnvalue = Encoding.Default.GetString (ReadBuffer) .Substring (0, streamSize); logs = returnvalue; return returnvalue;}} /// /// and The server interacts, sends a command and receives a 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; }} /// /// Interaction with the server, send a set of commands and receives the response.
/// summary> private bool dialog (str, str, string errstr) {for (int i = 0; i
")) Return False;} else {sendbufferstr =" Helo " MailServer Enter; if (! Dialog (sendbufferstr,")) Return False;} // sendbufferstr = "Mail from: <" from ">" Enter; if (! Dialog (SendBufferstr, "sender address error, or can't be empty")) Return False; // sendbuffer = new string [RecipientMaxNum]; for (int i = 0; i " enter;} if (! Dialog (sendbuffer, "recipient address incorrect)) Return False SendBufferstr = "Data" Enter; if (! Dialog (sendbufferstr, ")) Return False; sendbufferstr =" from: " fromname " <" from "> enter; sendbufferstr = "TO: = " Charset.toupper ()" B¡ " Base64Encode (RecipientName) " = " " <" Recipient [0] "> Enter; sendbufferstr = "cc:"; for (int i = 0; i ";} sendbufferstr = Enter; if (charset == ") {sendbufferstr =" Subject: " SUBJECT ENTER;} else {sendbufferstr
= "Subject:" "= ¡" charset.toupper () b¡ " " "=" 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 {sendbuf Ferstr = "charset = /" " " / "" enter;} // sendbufferstr = "Content-Transfer-Encoding: Base64" Enter; sendbuffrstr = "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; sendbufferstr = "content-disposition: attachment;" Enter; sendbufferstr = "filename = /" = " Charset.toupper ()" B¡ " Base64encode (filepath.substring (filepath.lastindexof (" // ") 1)) = / "" Enter enter; SendBufferstr = GetStream (filepath) enter enter;}} SendBufferstr = "------ = _ NextPart_000_00D6_01C29593.AAB31770 -" enter enter; SendBufferstr = enter "." Enter; if (! Dialog (SendBufferstr, "Error Letter Information")) Return False; SendBufferstr = "Quit" Enter; if (! Dialog (SENDBUFFERSTR, "Disconnect Error")) Return False; ns.close (); tc.close (); return true;} /// /// Send a mail 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 four;} /// /// Send email method /// summary> /// SMTP server information, such as "UserName: Passwordwww.smtpserver.com: 25", you can also remove some secondary information, 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: Passwordww.smtpserver.com: 25 ", You can also remove some times of information, such as www.smtpserver.com" param> /// sender mail address param> /// Recipient Address param> /// Recipient Name 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;