This is for
[Original] Email Send System (C # Based on SMTP Certification) http://www.lionsky.net/mywebsite/Article/List.aspx?id=430
When the revision is in order to write a service for the company, it has found the above address from the Internet, which is 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 a rewritten code: use system; use system.io; useing system.net; useing system.net.net.net.Sockets; useing system.collections;
Namespace Deep.sendemail {#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 const 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 m_charset = "GB2312"; /// / // Server Interaction Record /// summary> private stringbuilder m_logs = new stringbuilder ();
PRIVATE STRING M_ERRCODE;
/// /// SMTP error code hash table /// summary> private haShtable m_ERRCODEHT = new hashtable ();
/// /// SMTP correct code hash table /// summary> private haShtable m_rightcodeht = new hashtable ();
/// /// Up to the number of recipients /// summary> private int m_recipientmaxnum = 2;
/// /// Reupition time, in seconds unit /// summary> private int m_repeattime = 120;
/// /// server error or reject waiting time, in milliseconds /// summary> private int m_waittime = 20000;
/// /// Initialization Class new instance ////// / summary> public smtpmail () {smtpcodeadd ();} #Region Properties definition Attribute /// // / server interacts record, if found that the SMTP server 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 m_logs.tostring ();}}
/// /// Up to the number of recipients /// summary> public int RecipientMaxNum {set {m_recipientmaxnum = value;} get {return m_recipientmaxnum;}}}}
/// /// Set language code, the default setting is GB2312, if you don't need to be set to "" /// summary> public string charSet {get {returnim_charset;} set {this .m_charset = value;}}
/// /// Reupition time, in seconds unit //// summary> public int repeattime {get {return m_repeattime;} set {m_repeattime = value;
}
/// /// server error or rejection waiting time, in milliseconds /////////waittime {get {Return M_WaitTime;} set {m_waittime = value> 10000? Value: 10000 }}
#ndregion
#REGONMETHODS definition method
/// /// mail server domain name and verification information /// Shape, "User: pass@www.server.com: 25", can also save secondary information. Such as "User: Pass@www.server.com" or "www.server.com" /// summary> /// Enter your username, password, mail server domain name, port number param> /// Return to the mail server domain name param> /// Return Username param> /// Return Password param> /// Return port number param> /// Return to whether SMTP verification param> /// < returns> 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 (": ")); password = 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 = mailServer. Substring (0, Tempint);}}
/// /// Add mail attachment /// summary> /// Accessories absolute path param> private ilist addattachment (params string [] filepath) {ix ( FILEPATH == NULL ||) {return null;} ilist m_attachments = new system.collections.arraylist (); // message attachment list for (int i = 0; i /// Add a set of recipients (not more than m_recipientmaxnum), the parameters are the array of strings /// summary> /// < param name = "recipients"> save string array with a recipient address (no more than m_recipientMaxnum a) param> private Hashtable AddRecipient (params string [] recipients) {if (recipients == null || recipients.Length = = 0) {Return Null;} Hashtable RecipientList = new hashtable (); // Recipient list
For (int i = 0; i
/// /// Send email method /// summary> /// /// sender mail address param> /// Sendant Name param> /// Recipient address list param> /// Reconfite Name param> ///// Whether html mail param> /// Mail topic param> /// mail body param> / // attachment list Mail param> 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 password bool needSmtp = false; // if SMTP authentication is SetMailDomain (smtpServer, out mailServer, out userName, out password, out mailserverport, out needSmtp); if (mailServer.Trim () == "") {m_logs.Append ( " You must specify the 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 ("Too many recipients in one" 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 While (! (Useime> repeattime || issuccessful) { try {tcpClientObject = new TcpClient (mailServer, mailserverport); networkStreamObject = tcpClientObject.GetStream (); isSuccessful = SendEmail (networkStreamObject, needSmtp, mailServer, userName, password, recipients, from, fromName, recipientName, subject, priority.ToString (), 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 (isSuccessful!) {string n = Thread.CurrentThread.Name; Thread.Sleep (WaitTime);} useTime = ((TimeSpan) (DateTime.Now - dateTimeBegin)) Seconds;.}}} return isSuccessful;} #endregion
#Region Private Helper Functions
/// /// SMTP response code hash table /// summary> private void smtpcoded () {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 Not achievable "); M_ERRCODEHT.ADD (" 421 "," Service is not ready, close transmission channel "); M_ERRCODEHT.ADD (" 450 "," requested by mail operations are not completed, mailboxes are not available (for example, mailbox busy) " ); M_ERRCODEHT.ADD ("550", "requested by mail operations, mailboxes are unavailable (for example, mailboxes are not found, or irresisible)"); m_ERRCODEHT.ADD ("451", "abandon the required operation; In the process, "); M_ERRCODEHT.ADD (" 551 "," User is non-local, please try "); 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", "mailbox name is unavailable, the required operation is not executed (such as mailbox format error)"); M_ERRCODEHT.ADD ("432", "requires a password conversion"); m_ERRCODEHT.ADD ("534", "authentication mechanism is too simple"); m_ERRCODEHT.ADD ("538", "Currently requested authentication mechanism needs to encrypt") M_ERRCODEHT.ADD ("454", "Temporary Authentication Failure"); M_ERRCODEHT.ADD ("530", "Requires Certification");
m_rightcodeht.add ("220", "Service Ready"); M_rightCodeht.Add ("250", "Required Mail Operation"); m_rightcodeht.add ("251", "User is non-local, will forward to "); m_rightcodeht.add (" 354 "," starting mail input, end "in . ); m_rightcodeht.add (" 221 "," Service Close Transfer Channel "); M_rightCodeht.Add ( "334", "server response verification base64 string"); m_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);
/// /// will decode Base64 string to normal string /// //// String param> private string base64decode (String) Str) {byte [] barray; barray = convert.FromBase64String (str); return eNCoding.default.getstring (barray);}
/// ///> File stream /// summary> /// Anneter's absolute path param> private string getStream (string filepath) {byte [] by = null; system.io.filestream filestr = null; string streamstring = ""; try {// Establish file stream object FILESTR = new system.io.filestream (filepath, system.io.filemode.open); by = New byte [system.convert.toint32 (filestr.length)]; 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;}
/// /// Send SMTP command /// summary> 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.MESSAGE ENTER); Return False;} Return true;
/// /// receiving SMTP server response /// summary> 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.Message 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, send a command and receives the response. /// summary> /// A command param> 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 [rrcode]! = Null) {return true;} else {m_ERRCODE = RRCODE; RETURN FALSE;}} else {returnaf false;}}}
/// /// interacts with the server, sends a set of commands and receives the response. /// summary>
Private Bool Dialog (String [] Str, NetworkStream _NetworkStream) {for (INT i = 0; I
Return True;}
/// /// SendEmail /// summary> /// returns> 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 ();
// Perform SMTP verification if (needsmtp) {sendbuffer = new string [4]; sendbuffer [0] = "ehlo" mailserver enter; sendbuffer [1] = "auth login" enter; sendbuffer [2] = base64encode userName) ENTER; SendBuffer [3] = Base64Encode (password) ENTER; if (Dialog (SendBuffer, _NetworkStream!)) {return false;}} else {SendBufferstr = "HELO" mailServer ENTER; if (Dialog (! SendBufferstr, _NetworkStream) Return False;} // sendbufferstr = "Mail from: <" from "> Enter; if (! Dialog (SendBufferstr, _NetworkStream) Return False;
// sendbuffer = new string [m_recipientmaxnum]; for (int i = 0; i " Enter;
}
IF (! Dialog (sendbuffer, _networkstream) Return False; sendbufferstr = "data" enter; if (! Dialog (sendbufferstr, _networkstream) Return False;
SendbufferstrBuilder.Append ("from:" " " < from "> enter); sendbufferstrbuilder.Append (" to: =? " Charset.toupper () " b? " Base64encode (RecipientName ) "? =" "<" enterbufferstrbuilder.append ("cc:"); for (int i = 0; i ,");} sendbufferstrbuilder.append (enter);
SendBufferstrBuilder.Append ((Subject == String.empty || Subject == NULL)? "Subject:": ((charset == ")? (" Subject: Subject) :( "Subject:" " =? " CHARSET.TOUPPER () "? B? " " = ")) " SendBufferstrBuilder.Append ("x-priority: priority enter); sendBufferstrBuilder; 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);}
if (isHtml) {if (! 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_dragon5206367771063 _ =====" enter); sendbufferstrbuilder.append ("Content-type: multipart / alternative;" enter); // Content format and separator sendbufferstrbuilder.Append ("Boundary = /" ===== 003_Dragon520636771063 _ ===== / "" enter enter);} sendbufferstrbuilder.Append ("- ====== 003_dragon520636771063_ =====" enter); SendbufferstrBuilder.Append ("Content-Type: Text / Plain;" Enter); SendBufferstrBuilder.Append ((Charset == ")? (" Charset = / "ISO-8859-1 /") :( ") = / "" " " / "")) Enter); sendBufferstrBuilder.Append ("Content-Transfer-Encoding: Base64" Enter Enter); sendbufferstrbuilder.Append (Base64Encode " HTML format, please select HTML to view ") Enter Enter); sendbufferstrbuilder.append (" - ====== 003_dragon520636771063 _ ===== " enter);
SendBufferstrBuilder.Append ("Content-Type: Text / HTML;" Enter); sendBufferstrBuilder.Append ((Charset == ")? (" Charset = / "ISO-8859-1 /") :( ") :(" Charset = / "" " " / "")) 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 ("- ====== 001_Dragon303406132050 _ ======" ENTER);} sendbufferstrbuilder.Append ("Content-Type: Text / Plain;" Enter); sendbufferstrbuilder.Append ((charset == " )? ("Charset = /" ISO-8859-1): ("Charset = /" "/" ")) " SendBufferstrBuilder.Append ("Content-Transfer);" Content-Transfer -Encoding: Base64 " ENTER ENTER); SendBufferstrBuilder.Append (Base64Encode (Body) ENTER);} // sendbufferstr =" Content-Transfer-Encoding: Base64 " Enter; IF (ATT Achments! = null && attachments.count! = 0) {for (int i = 0; i
// 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;}
#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 {m_logs. Append ("Error: Recipient too many"); return false;}} /// /// Add a set of portable recipients (no more than 10), parameter is the array of strings /// < / summary> /// Save strings (no more than 10) (no more than 10) param> public bool addrecipientbcc (string [] str) {for (int i = 0) i
* / #Ndregion}
/// // / message Send priority /// summary> public enum priority {high, normal, low}
#ndregion
}