Email Send System (C # + Based on SMTP Certification) 2.0 (Favorites)

zhaozj2021-02-12  135

Email Send System (C # Based on SMTP Certification) 2.0

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 /// 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 "" /// private string _charset = "GB2312";

///

/// sender address /// private string _from = ""

///

/// sender name /// private string _fromname = ""; /// /// Reply email address /// /// public String replyto = "";

///

/// Recipient name /// private string _recipientname = "

///

/// Recipient list /// private haShtable recipient = new hashtable ();

///

/// mail server domain name /// private string mailserver = "

///

/// Mail server port number /// private int mailserverport = 25;

///

/// SMTP authentication User Name /// private string username = "";

///

/// SMTP authentication password /// private string password = "";

///

//: Do not need SMTP verification /// private bool esmtp = false;

///

/// is HTML mail /// private bool _html = false;

///

/// Email attachment list /// private ilist attachments;

///

/// message Send priority, can be set to "High", "Normal", "Low" or "1", "3", "5" /// Private String Priority = "Normal";

///

/// mail topic /// private string _subject;

///

/// message body /// private string _body; /// /// secret recipient list /// /// private hashTable RecipientBCC = new hashtable ();

///

/// Repair number /// private int RecipientNum = 0;

///

/// Up to the number of recipients /// private INT RecipientMaxNum = 5;

///

/// Double (/ summary> /// private int recipientbccnum = 0; /// /// error message feedback /// private String errmsg;

///

/// TcpClient object for connection server /// private tclient tc;

///

///// private networkStream ns; /// /// server interactive record /// private string logs = "

///

/// SMTP error code hash table /// private hashtable errcodeht = new hashtable ();

///

/// SMTP correct code hash table /// private hashtable rightcodeht = new hashtable ();

///

/// Initialization new instance ///// / summary> public smtpmail () {attachments = new system.collections.arrayList ( }

#Region Properties

///

/// mail topic /// public string subject {get {return this._subject;} set {THIS._SUBJECT = VALUE;}}

///

/// message body /// public string body {get {return this._body;} set {THIS._BODY = value;}}

///

/// sender address /// 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 "" /// public string charset {get {returnim "}}} set {THIS ._charset = value;}}

///

/// sender name ////// public string fromname {get {return this._fromname;} set {this._fromname = value;}}

///

/// Recipient Name /// 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" /// 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 /// 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" /// 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 /// public bool html {get {returnim {this._html = value;}}

///

/// error message feedback /// 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. /// public string logs {get {return logs;}}

///

/// Most recipients /// public int RecipientMaxnum {set {recipientmaxnum = value;}}

#ndregion

#Region Methods

///

/// Add mail attachment /// /// attachment absolute path 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 /// /// Save a string with the recipient address array (not more than recipientmaxnum a) 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. /// public bool send () {if (mailserver.trim () == "" {throw ("Recipient", "must specify SMTP server"));

Return sendemail ();

///

/// Send email method /// ///

Interest, such as "www.smtpserver.com" public bool send (string smtpserver) {maildomain = SMTPSERVER; RETURN Send ();} ///

/// Send Mail Method /// /// SMTP server information, such as "UserName: Password@www.smtpserver.com: 25", you can also remove some times

Interest, such as "www.smtpserver.com" /// sender Mail address /// sender name < / param> /// Recipient address /// Referth /// Whether html mail /// Mail topic /// mail body 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 /// /// Recipient Address Private Bool AddRecipient (String Recipients) {IF RecipientNum

"));}}

Void Dispose () {if (ns! = null) ns.close (); if (tc! = null) tc.close ();} ///

/// SMTP response code hash table /// 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 /// /// String private string base64encode to encode Private String Base64Encode ) {Byte [] barray; barray = encoding.default.getBytes (str); return convert.tobase64string (barray);} /// /// Decoding the base64 string is normal string /// /// String private string base64decode (string str) {byte [] barray; barray = convecture.default.getstring (STR); Return encoding.default.getstring Barray;}

///

///> File stream /// /// Accessories's absolute path 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 /// 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 /// 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. /// /// A command to send /// If the error, the information you want to feedback 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. ///

Private bool dialog (str, str, string errstr) {for (int i = 0; i

Return true;} ///

/// sendemail /// 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 /// /// Recipient address 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 / /// /// Save a receipt Human address string array (no more than 10) public bool addrecipientbcc (string [] str) {for (int i = 0; i

#ndregion}

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

New Post(0)