Rewrived "[Original] Email Send System (C # + Based on SMTP Certification)"

xiaoxiao2021-03-06  41

This is for [Original] Email Send System (C # Based on SMTP Certification) http://www.lionsky.net/mywebsite/Article/List.aspx?id=430's revision is available from the Internet I found the above address, I am very grateful to the original author's creative labor. The purpose of rewriting is to adapt to the requirements of service operation: 1. Adapt to multi-thread requirements, sending mail services can be run in the background, will be considered as exclusive resource with the SMTP server. 2 , Return the logo that is not successfully sent. 3, streamlined attributes, methods, information related to mail no longer act as an attribute, but as the parameters of Send; only an overloaded Send method is announced. In this class as the base class, the interface method of the notification service requires.

The following is the code rewritten: using System; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; using System.Collections; using System.Threading; namespace Deep.SendEmail {#region AspNetPager Server control ///

/// message can be transmitted /// public class smtpmail {private const string enter = "/ r / n with SMTP mail service or any SMTP server built in Microsoft Windows 2000 "; /// /// set language code, the default setting is GB2312, if you do not need to be set to" "/// private string m_charset =" GB2312 "; /// // / server interactive record /// private stringbuilder m_logs = new stringbuilder (); private string m_ERRCODE; /// /// SMTP error code hash table /// private Hashtable m_ERRCODEHT = new hashtable (); /// /// SMTP correct code hash table /// private haShtable m_rightcodeht = new hashtable (); /// /// Up to Piece of people /// private int m_recipientmaxnum = 2; /// /// Reupition time, in seconds /// private int m_repeattime = 120; /// // server error or reject waiting time, in milliseconds Bit /// private int m_waittime = 20000; /// /// Initialization new instance /// Public SMTPMAIL ();} #Region Properties Defines Properties /// /// Server Interaction Record, if this component does not use the SMTP server, please send me the logs when the error (Lion- A@sohu.com), I will find out the cause as soon as possible.

/// public string logs {rary m_logs.tostring ();}} ///

/// Up to the number of recipients /// public int RecipientMaxNum {set {m_recipientmaxnum = Value;} get {return m_recipientmaxnum;}}}} /// /// Set language code, the default setting is GB2312, if it is not required to be set to "" /// public string charSet { Get {return this.m_charset;} set {this.m_charset = value;}} /// /// repetition time, in seconds unit /// public int REATTIME {Get {Return M_RepeAttime; } Set {m_repeattime = value;}} /// /// server error or reject waiting time, in milliseconds /// public int waittime {get {return m_waittime;} set { m_waittime = value> 10000? Value: 10000;}} #endregion #region method Methods definition method /// /// mail server domain name and verification information ///-shaped as: "User: pass@www.server.com : 25 ", you can also save subsistence information.

Such as "User: Pass@www.server.com" or "www.server.com" /// /// Enter your username, password, mail server domain name, port number /// Return to the mail server domain name /// Return Username /// Return Password /// Return port number /// Return to whether SMTP verification /// < returns> private bool SetMailDomain (string mailDomain, out string mailServer, out string mailServerUserName, out string password, out int mailserverport, out bool needSmtp) {bool isRight = false; // given initial MailServer = string as output .Empty; mailServerUserName = String.Empty; password = String.Empty; mailserverport = 25; needSmtp = false; mailServer = mailDomain.Trim (); int tempint; if (! mailServer = "") {tempint = mailServer.IndexOf ( " @ "); Isright = true; if (Tempint! = - 1) {string str = mailserver.substring (0, tempint); mailserverusername = str.substring (0, str .indexof (": ")); pass Word = str.substring (str.indexof (":") 1, str.Length-str.indexof ("::") - 1); Needsmtp =! (password == string.empty); mailserver = maildomain.substring (Tempint 1, Maildomain.Length-Tempint-1);} tempint = mailserver.indexof (":"); if (Tempint! = -1) {mailserverport = system.convert.toint32 (MailServer.Substring (Tempint 1 , MailServer.Length-Tempint-1)); MailServer = mailser.substring (0, TemPint);

}}}}} ///

/// Add mail attachment /// /// Accessories absolute path private ilist addattachment (params string ] filepath) {if (filepath == null || filepath.Length == 0) {Return null;} ilist m_attachments = new system.collections.ArrayList (); // message attachment list for (int i = 0; i < FilePath.Length; i ) {if (filepath [i])) {m_attachments.add (filepath [i]);} else {m_logs.Append ("Error: Did not find a file name" filepath [i ] "Attachment file!" Enter);}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} /// /// Add a set of recipients (not more than M_recipientmaxnum), the parameter is the array of strings /// /// Save strings (not more than m_recipientmaxnum) private haShtable addRecipient (params string [] recipients) {if (Recipients == NULL) {ix || Recipients.Length == 0) {RETURN NULL;} Hashtable RecipientList = new hashtable (); // Recipient list for (int i = 0; i /// Send Mail Method // / /// SMTP server information, such as "UserName: Password@www.smtpserver.com: 25", you can also remove some time you want, such as "www.smtpserver.com " /// sender mail address ///

Sendant Name /// Recipient address list /// Reconfite Name ///// Whether html mail /// Mail topic /// mail body / // attachment list Mail public bool Send (string smtpServer, string from, string fromName, string [] recipientADD, string recipientName, bool isHtml, string subject, priority priority, string body, String [] filepath) {// If the recipient is more transmitted at the same time, sending if (RecipientAdd.Length> RecipientMaxNum) {string [] RecipientAdd1 = new string [RecipientMaxNum]; string [] recipientADD2 = new string [recipientADD.Length - RecipientMaxNum]; for (int i = 0; i 2048) {m_logs.Remove (0, m_logs.Length);} string mailServer = "" ; // mail server domain name int mailserverport = 25; // mail server port number string username = ""; // SMTP authentication User name STRING password = ""; // SMTP authentication is used by password BOOL NEEDSMTP = FALSE : // Do not require SMTP to verify setmails (SMTPServer, Out Mail Server, Out Userverport, Out Needsmtp); if (MailServer.trim () == "

) {M_logs.Append ( "must specify an SMTP server" ENTER); return false;} IList attachments = AddAttachment (filePath); // mail attachment list Hashtable recipients = AddRecipient (recipientADD); // recipient list if (recipients == NULL || Recipients.count == 0) {m_logs.Append ("must specify" Enter); return false;} if (Recipients.count> RecipientMaxNum) {m_logs.append ("One Send too many pieces " ENTER); return false;} bool isSuccessful = false; lock (this) {TcpClient tcpClientObject = null; // TcpClient objects, for connecting the server NetworkStream networkStreamObject = null; // NetworkStream objects DateTime dateTimeBegin = DateTime .Now; int useTime = 0; (! (useTime> RepeatTime || isSuccessful)) while {try {tcpClientObject = new TcpClient (mailServer, mailserverport); networkStreamObject = tcpClientObject.GetStream (); isSuccessful = SendEmail (networkStreamObject, needSmtp, mailServer , Username, Password, Recipients, from, fromname, RecipientName, Subject, Priority.toT7tring (), Attachments, Ishtml, body);} catch (Exception e) {m_logs.Append ( "Error:"!! e.Message ENTER);} finally {if (networkStreamObject = null) networkStreamObject.Close (); if (tcpClientObject = null) tcpClientObject .Close (); if {string n = Thread.CurrentThread.Name; Thread.Sleep (WaitTime);} (isSuccessful!). useTime = ((TimeSpan) (DateTime.Now - dateTimeBegin)) Seconds;}}} return isSuccessful } #Endregion #region private helper functions ///

/// SMTP response code hash table ///

Private void smtpcodeadd () {m_ERRCODEHT.ADD ("500", "Mailbox Address Error"); m_ERRCODEHT.ADD ("501", "Parameter Format Error"); m_ERRCODEHT.ADD ("502", "command is not implemented") M_ERRCODEHT.ADD ("503", "Server requires SMTP verification"); m_ERRCODEHT.ADD ("504", "command parameters are not implemented"); m_ERRCODEHT.ADD ("421", "service is not ready, turn off Transfer Channel" ); M_ERRCODEHT.ADD ("450", "requested by mail operations, mailboxes are not available (for example, mailbox busy)"); m_errcodeht.add ("550", "required mail operations are not completed, mailboxes are not available ( For example, mailbox is not found, or inseparable) "); m_ERRRCODEHT.ADD (" 451 "," Abandon the requirements of the requirements; error during processing "); M_ERRCODEHT.ADD (" 551 "," User Non-local, please try < Forward-path> "); m_ERRCODEHT.ADD (" 452 "," system storage is insufficient, the required operation is not executed "); m_ERRCODEHT.ADD (" 552 "," excess storage allocation, required operation is not executed "); M_ERRCODEHT.ADD ("553", "mail address is not available, the required operation is not executed (such as mailbox format error)"); m_errcodeht.add ("432", "require a password conversion"); m_ERRRCODEHT.ADD ("534 "" The "certification mechanism is too simple"); m_errcodeht.add ("538", "Current Request Certification Mechanism Requires"); M_ERRCODEHT.ADD ("454", "Temporary Certification Failure"); m_ERRCODEHT.Add ("530 "," Need to authenticate "); m_rightcodeht.add (" 220 "," service ready "); m_rightcodeht.add (" 250 "," required mail operation "); m_rightcodeht.add (" 251 "," users Local, will forward to "); m_rightcodeht.add (" 354 "," starting mail input, end "in . ); m_rightcodeht.add (" 22 1 "," Service Close Transfer Channel "); M_rightCodeht.Add (" 334 "," Server Response Validation Base64 String "); M_rightCodeht.Add (" 235 "," Verification Success ");} ///

/// The string is encoded as Base64 string /// ///

"Str"> String private string base64encode (string str) {byte [] barray; barray = encoding.default.getbytes (str); return convert.tobase64string (barray);} /// < Summary> /// Decoding Base64 strings to normal strings /// String private string base64decode (string string string string string Str) {BYTE [] Barray; barray = convert.FromBase64String (STR); return encoding.default.getstring (barray);} ///

/// //// < Param name = "filepath"> Absolute path private string getStream (string filepath) {byte [] by = null; system.io.filestream filestr = null; string streamstring = "; try {// Establishment File Flow Object FILESTR = New System.IO.FileStream (filepath, system.io.filemode.Open); by = new byte [system.convert.toint32 (filestr.rength)]; fileStr.Read (by, 0, by. Length); streamstring = system.convert.tobase64string (by);} catch (exception ex) {// write error log m_logs.Append ("error:" EX.MESSAGE ENTER);} finally {if (filester! NULL) {FileStr.Close ();}} return streamString;} /// /// SMTP commands are sent /// private bool SendCommand (string str, NetworkStream _NetworkStreamObject) {byte [] WriteBuffer; if ( str == null || str.Trim () == String.Empty) {return true;} m_logs.Append (str ENTER); WriteBuffer = Encoding.Default.GetBytes (str); try {_NetworkStreamObject.Write (WriteBuffer, 0, WriteBuffer.Length);} catch (exception ex) {// Write log m_logs.append ("error:" ex. measure enter); return false;

} Return true;} ///

/// receiving SMTP server response /// private string RecvResponse (NetworkStream _NetworkStreamObject) {int StreamSize = 0; string ReturnValue = String.Empty; byte [] ReadBuffer = New byte [1024]; try {streamsize = _networkStreamObject.read (readbuffer, 0, readbuffer.Length);} catch (exception ex) {// Write log m_logs.append ("error:" ex. measure enter); m_ErrCode = ex.Message; return "false";} if (streamSize == 0) {return ReturnValue;} else {ReturnValue = Encoding.Default.GetString (ReadBuffer) .Substring (0, streamSize); m_logs.Append (ReturnValue ENTER); RETURN RETURNVALUE;}}} /// /// interacts with the server, sends a command and receives the response. /// /// A command private bool dialog (String Str, NetworkStream _networkStream) {if (str.trim) {if (str.trim) {if (str.trim) {if (str. " ) == "" "} {STRING RR = recvresponse (_networkstream); if (rr ==" false ") {RRING RRINGSE;} string rrcode = r.substring 0, 3); if (m_rightcodeht [rcode]! = Null) {return true;} else {m_ERRCODE = rrcode; return false;}}}} /// /// Send a set of commands and receive response.

/// private bool dialog (String [] str, networkStream _networkstream) {for (int i = 0; i /// SendEmail /// /// private bool SendEmail (NetworkStream _NetworkStream, bool needSmtp, string mailServer, string userName, string password, Hashtable recipients, string from, string fromName, string recipientName, string subject, string priority, IList attachments, bool isHtml, string body) {// verify network connections are correct if (m_RightCodeHT [RecvResponse (_NetworkStream) .Substring (0,3)] == null) {return false;} string [] SendBuffer; string SendBufferstr; StringBuilder SendBufferstrBuilder = new StringBuilder (); // SMTP authentication if (needSmtp) {SendBuffer = new String [4]; SendBuffer [0] = "EHLO" MailServer Enter; sendbuffler [1] = "auth login" enter; sendbuffler [2] = base64encode (username) ENTER; sendbuffer [3] = Base64Encode (PA ssword) ENTER; if) (Dialog (SendBuffer, _NetworkStream!) {return false;}} else {SendBufferstr = "HELO" mailServer ENTER; if) return false (Dialog (SendBufferstr, _NetworkStream!);} // SendBufferstr = "Mail from: <" from "> ENTER; if (! Dialog (sendbufferstr, _networkstream) Return false; // sendbuffer = new string [m_recipientmaxnum]; for (int i = 0; i " enter;

(! Dialog (SendBuffer, _NetworkStream))} if return false; SendBufferstr = "DATA" ENTER; if return false; SendBufferstrBuilder.Append ( "From:" (Dialog (SendBufferstr, _NetworkStream)!) FromName "<" From "> enter); sendbufferstrbuilder.Append (" to: =? " charset.toupper () "? b? " base64encode (recipientname) "? = " " <" Recipients [0] "> Enter); sendBufferstrBuilder.Append (" cc: "); for (int i = 0; i );} SendBufferstrBuilder.Append (Enter); SendBufferstrBuilder.Append ((Subject == String.empty || Subject == NULL)?" Subject: ":( ("" Subject: " Subject): (" Subject: " " =? " CHARSET.TOUPPER () "? B? " Base64Encode (Subject) "? = ") )) ENTER); SendBufferstrBuilder.Append ( "X-priority:" priority ENTER); SendBufferstrBuilder.Append ( "X-MSMail-priority:" priority ENTER); SendBufferstrBuilder.Append ( "Importance:" priority ENTER); SendBufferstrBuilder.Append ( "X-Mailer: Lion.Web.Mail.SmtpMail Pubclass [cn]" ENTER); SendBufferstrBuilder.Append! ( "MIME-Version: 1.0" ENTER); if (attachments = null && attachments.Count ! = 0) {SendBufferstrBuilder.Append ("Content-Type: Multipart / Mixed;" ENTER); sendbufferstrbuilder.Append ("

Boundary = / "======= (ISHTML?" 001_dragon520636771063 _ ":" 001_dragon303406132050 _ ") " ==== / " ENTER ENTER);}}}}}}} {i (attachments! = null && attachments.Count == 0) {SendBufferstrBuilder.Append ( "content-Type: multipart / alternative;" ENTER); // content format and separators SendBufferstrBuilder.Append ( "boundary = /" ===== 003_Dragon520636771063_ = ==== / "" Enter ENTER); sendBufferstrBuilder.Append ("this is a multi-part message in mime format." ENTER ENTER);} else {sendbufferstrbuilder.Append ("this is a multi-part message in MIME format " ENTER ENTER); SendBufferstrBuilder.Append (" - ===== 001_Dragon520636771063 _ ===== " ENTER); SendBufferstrBuilder.Append (" Content-Type:. multipart / alternative; " ENTER); // Content format and separator sendbuffrstrbuilder.Append ("boundary = /" ===== 003_dragon520636771063 _ ===== / "" "" enter enter);} sendbufferstrbuilder.Append ("- === == 003_dragon520636771063 _ ===== " enter); sendBufferstrBuilder.Append (" Content-Type: Text / Plain; " ENTER); sendbuff ErstrBuilder.Append ((Charset == ")? (" Charset = / "ISO-8859-1): (" Charset = / " " / "")) ENTER); sendbufferstrbuilder.append ("Content-Transfer-Encoding: Base64" Enter Enter);

SendBufferstrBuilder.Append (Base64Encode ( "message content to HTML format, select the HTML view mode") ENTER ENTER); SendBufferstrBuilder.Append ( "- ===== 003_Dragon520636771063 _ =====" ENTER); SendBufferstrBuilder .Append ("Content-Type: Text / HTML;" ENTER); sendbufferstrbuilder.Append ((Charset == ")? (" Charset = / "ISO-8859-1) :(" "" " / "" "" "")) Enter); sendBufferstrBuilder.Append ("Content-Transfer-Encoding: Base64" Enter Enter); sendbufferstrbuilder.Append (Base64Encode (Body) ENTER ENTER); SendBufferstrBuilder.Append ( "- ===== 003_Dragon520636771063 _ ===== -" ENTER);} else {if (attachments = null && attachments.Count = 0) {SendBufferstrBuilder.Append (!! "- ===== 00132050 _ =====" ENTER);} sendbufferstrbuilder.Append ("Content-type: text / plain;" enter); sendbufferstrbuilder.Append ((charset == ") ("Charset = /" ISO-8859-1 / ""): ("Charset = /" "/" ")) Enter; sendbufferstrbuilder.Append (" Content-Transfer- EN coding: base64 " ENTER ENTER); SendBufferstrBuilder.Append (Base64Encode (body) ENTER);} // SendBufferstr =" Content-Transfer-Encoding:! base64 " ENTER; if (attachments = null && attachments.Count ! = 0) {for (int i = 0; i

) {String filepath = (string) attachments [i]; sendbufferstrbuilder.Append ("- =====" (Ishtml? "001_dragon520636771063 _": "001_dragon303406132050_") "=====" enter); ENTER); // SendBufferstr = "Content-Type: application / octet-stream" ENTER; SendBufferstrBuilder.Append? ( "Content-Type: text / plain;" ENTER); SendBufferstrBuilder.Append ( "name = /" = " Charset.toupper () "? B?" Base64encode (filepath.substring (filepath.lastindexof ("//") 1)) "? = /" " Enter); sendbufferstrbuilder.Append (" Content-Transfer -Encoding: Base64 " ENTER); SendBufferstrBuilder.Append (" Content-Disposition: attachment; " ENTER); sendBufferstrBuilder.Append (" filename = / "=?" Charset.toupper () "? B?" Base64Encode (filepath.Substring (filepath.LastIndexOf ( "//") 1)) " ENTER ENTER)" = /? "; SendBufferstrBuilder.Append (GetStream (filepath) ENTER ENTER);} SendBufferstrBuilder.Append ("- =====" (iSHTML? "001_dragon520636771063 _": "001_dragon303406132050_") "===== -" Enter Enter);} SendBufferstrBuilder.Append ( "." ENTER ENTER); SendBufferstr = SendBufferstrBuilder.ToString (); if (! Dialog (SendBufferstr, _NetworkStream)) return false; SendBufferstr = "QUIT" ENTER; if (Dialog (SendBufferstr, _NetworkStream)!) Return False; Return True;} #endregion #region / * ///

转载请注明原文地址:https://www.9cbs.com/read-72160.html

New Post(0)