SMTP mail sending class with C #

xiaoxiao2021-03-06  51

/ ********************* CREATED by chen ********************************* **

* If you feel that I have a good article, please refer to the work of the work, explanation

* Source and original author, Thank you !!! email: Aishen944-sohu.com

*********************************************************** ***************** / using system; use system.io; use system.net; using system.net.sockets; using system.collections; using system.collections; using system.collections; using system.collections; using system.collections; .Collections.Specialized; using ksn.exceptions; use ksn.validate; namespace ksn.web.mail {///

/// mail content /// public class mailmessage {private string sender = null; private StringCollection receivers = new StringCollection (); private string subject = ""; private string xMailer = ""; private StringCollection attachments = new StringCollection (); private MailEncodings mailEncoding = MailEncodings.GB2312; private MailTypes mailType = MailTypes.Html; private byte [] mailbody = null; /// /// Get or set the sender /// public string sender {get {return this.sender;} set {this.sender = value;}} /// /// Get recipient address collection /// public stringcollection receivers {get {return this.Receivers;}} /// /// Get or set mail topic / // Public String Subject {Get {return this.subject;} set {this.subject = value;}} /// /// Get or sets mail delivery //// public string xmailer {get {return. XMAiler;} set {this.xmail = value;}} /// /// Get an attachment list /// public stringcollection attachments {get {return this.attachments;}} /// /// Get or set up the encoding method /// public mailencodings mailencoding {get {return this.mailencoding;} set {this.mailencoding = value;}} /// /// Get Or set the mail format /// public mailtypes mailtype {get {return this.mailType;

} Set {this.mailType = value;}} ///

/// Get or set the message body /// public byte [] mailbody {get {return this.mailbody;} set {THIS. Mailbody = value;}}} /// /// message encoded /// public enum mailencodings {GB2312, ASCII, Unicode, UTF8} /// /// mail format // / public enum mailtypes {html, text} /// /// SMTP server authentication mode /// public enum smtpvalidatetypes {/// /// No verification /// /// General Auth login Verification /// login, /// /// General Auth Plain Verification /// < / summary> plain, /// /// CRAM-MD5 verification /// cramd5} /// /// mail send class /// public class ksn_smtp { #REGON "MEMBER FIELDS" /// /// Connection Object /// private tclient tc; /// /// network stream /// private networkStream NS; /// /// Error code dictionary /// private stringDictionary error erroorcodes = new stringDictionary (); /// /// operation is performed Work after the Response Code Dictionary /// private stringDictionary rightcodes = new stringDictionary (); /// /// 错 错 错 消 消 消 /// private string errorMessage = "" ; /// /// Record operation log /// private string logs = ""; /// /// host login verification mode /// private StringCollection ValidateTypes = new stringCollection (); /// /// Retinal constant /// private const string crlf = "/ r / n"; private string servername = "smtp";

private string logPath = null; private string userid = null; private string password = null; private string mailEncodingName = "GB2312"; private bool sendIsComplete = false; private SmtpValidateTypes smtpValidateType = SmtpValidateTypes.Login; #endregion #region "propertys" ///

/// Gets the error message in the last program /////////mary> public string errorMessage {get {return}} /// /// Get or set the log output Path /// public string logpath {get {return this.logpath;} set {this.logpath = value;}} /// /// Get or set the account number of login SMTP server ///// public string userid {get {return} set {this.userid = value;}} /// /// Get or set the password of the login SMTP server /// Public String Password {get {return this.password;} set {this.password = value;}} /// /// Get or set to use the login SMTP server authentication mode /// public SMTPVALIDATYPES SMTPVALIDATETYPE {Get {Return this.smtpvalidateType;} set {this.smtpvalidatetype = value;}} #ENDREGION #Region "Construct Functions" /// /// Constructor /// /// hostname /// Port public ksn_smtp (string server, int port) {tc = new tcpclient (server, port); ns = tc.getStream (); this.serverName = Server; this.initialfields ();} // / /// constructor /// /// host IP /// port public KSN_SMTP (iPadDress IP, INT Port) {ipendPoint Endpoint =

NEW IPENDPOINT (IP, Port); tc = new tcpclient (endpoint); ns = tc.getStream (); this.servername = IP.TOString (); this.initialfields ();} #endregion #region "Methods" Private Void Initialfields () // Initialization connection {logs = "=================" DATETIME.NOW.TOLONGDATESTRING () " " DATETIME.NOW.TOLONGTIMESTRING () "= = =============== " CRLF; // ****************************** ******************************************************************************** *********************************************************** ******** ErrorCodes.add ("421", "Service is not ready, shut down"); ErrorCodes.Add ("432", "need a password conversion"); errorcodes.add ("450" "The required mail operation is not completed, the mailbox is unavailable (eg mailbox busy)"); ErrorCodes.add ("451", "Abandon the required operation, the required operation is not implemented"); erroorcodes.add ("452" "System storage is insufficient, the required operation is not completed"); errorcodes.add ("454", "temporary authentication failed"); ErrorCodes.Add ("500", "Email address error"); erroorcodes.add (" 501 "," Parameter Format Error "); ErrorCodes.Add (" 502 "," command is not implemented "); errorcodes.add (" 503 "," The order is incorrect "); ErrorCodes.Add (" 504 ", "Command parameters are not implemented"); ErrorCodes.Add ("530", "Requirements"); ErrorCodes.Add ("534", "Certification Mechanism is too simple"); ErrorCodes.Add ("538", "current request The authentication mechanism needs to be encrypted "); ErrorCodes.Add (" 550 "," The current mail operation is not completed, the mailbox is unavailable (eg mailbox not found or mailbox cannot be used) "); errores.add (" 551 "," user Non-local, please try "); errorcodes.add (" 552 "," excess storage allocation, the formulated operation is not completed "); ErrorCodes.Add (" 553 "," mailbox name is not available, such as : Format Errors in Email Address; ErrorCodes.Add ("554", "Transfer Fail"

); Erroorcodes.add ("535", "user authentication failed"); // ****************************************** *********************************************************************************** *********************************************************** ********* Rightcodes.add ("220", "Service Ready"); RightCodes.add ("221", "Service Turn Transfer Transfer Channel"); RightCodes.Add ("235", "successful "); RightCodes.Add (" 250 "," required mail operation "); RightCodes.add (" 251 "," non-local user, will forward to "); Rightcodes.Add (" 334 "," Server Response Validation Base64 String "); RightCodes.Add (" 354 "," Start Mail Enter, End "in . "); // Read System Responding StreamReader Reader = New StreamReader (NS ); Logs = reader.readLine () CRLF;} ///

/// Send command /// /// private string SendCommand (String Cmd, Bool Ismails) {IF (cmd! = null && cmd.trim ()! = string.empty) {byte [] cmd_b = null; if (! ismails) / / is not email data cmd = CRLF;

Logs = cmd; // Start Write Mail Data IF (! Ismails) {CMD_B = Encoding.ASCII.GETBYTES (CMD); ns.write (cmd_b, 0, cmd_b.length);} else {cmd_b = encoding.getencoding this.mailEncodingName) .GetBytes (cmd); ns.BeginWrite (cmd_b, 0, cmd_b.Length, new AsyncCallback (this.asyncCallBack), null);} // read the server response StreamReader reader = new StreamReader (ns); string response = reader.ReadLine (); logs = response CRLF; // check the status code string statusCode = response.Substring (0,3); bool isExist = false; bool isRightCode = true; foreach (string err in this.errorCodes. Keys) {if (statusCode == err) {isExist = true; isRightCode = false; break;}} foreach (string right in this.rightCodes.Keys) {if (statusCode == right) {isExist = true; break;} } // According to the status code, the next action IF (! ISexist) // is not a legitimate SMTP host {this.setd ("Not a legitimate SMTP host, or server deny service");} else if (! Isrightcode) / / The command has not been successfully executed {this.seterror (statuscode ":" this.errorcodes [statu SCODE // The else // command successfully executed {this.ErrorMessage = "";} Return Response;}}} ///

/// Log in to the SMTP server via auth login /// private void landingByLogin () {string base64UserId = this.convertBase64String (this.UserID, "ASCII"); string base64Pass = this.convertBase64String (this.Password, "ASCII"); // handshake this.sendCommand ( " Helo " this.servername, false); // Start landing this.sendcommand (" Auth login ", false); this.sendcommand (Base64Userid, false); this.sendcommand (Base64Pass, false);} ///

/// Login Server /// private void landingByplain () {string null = (); string loginstr = null this.userid null this.password null this.password String Base64loginstr = this.convertbase64String (Loginstr, "ASCII"); // Handshake this.sendcommand ("Helo" this.servername, false); // Login this.sendCommand (Base64loginstr, false);} /// < Summary> /// Log in /// private vid landingBycrammd5 () {// Handshake ThisndCommand ("Helo" this.servername, false; // Login String Response = THIS .sendcommand ("Auth CRAM-MD5", FALSE); // Get the logo returned by the server String Identifier = response.remove (0, 4); // encrypted with MD5 KSN_MACTRIPLEDES MAC = New KSN_MACTRIPLEDES (); mac.key = This.Password; mac.data = encoding.ascii.getbytes; string hash = mac.getHashValue (); // Send User account information this.sendcommand (this.userid " hash, false);} // /

/// Send mail /// /// public bool sendmail (MailMAGE Mail) {bool issended = true; try {// detection send mail Necessary Condition IF (Mail.Sender == Null) {this.seEterror ("No Sender");} f (mail.receivers.count == 0) {this.seEterror ("At least one recipient" );} If (this.smtpvalidatetype! = SMTPVALIDATEPES.NONE) {if (this.userid == null || this.password == null) {this.seterror ("The current setting requires SMTP verification, but no login account ");}} // Start landing Switch (this.smtpvalidatetype) {Case SMTPVALIDATEPES.NONE: this.sendcommand (" Helo " this.servername, false; case smtpvalidatetypes.login: this.landingbyLogin ();

break; case SmtpValidateTypes.Plain: this.landingByPlain (); break; case SmtpValidateTypes.CRAMMD5: this.landingByCRAMMD5 (); break; default: break;} // initialize mail session (corresponding to SMTP command mail) this.sendCommand ( "mail From: <" mail.sender "> ", false); // Identify the recipient (corresponding SMTP command RCPT) Foreach (String receive in mail.receivers) {this.sendcommand (" rcpt to: <" receive " > ", false);} // Logo Start Entering Mail Content (DATA) This.sendCommand (" DATA ", FALSE); // Start writing mail content string message =" Subject: " mail.subject crlf; message = "X-mailer:" mail.xmailer crlf; message = "mime-version: 1.0" CRLF; if (mail.ttachments.count == 0) // No attachment {if (mail.mailtype == mailtypes. TEXT) // Text Format {Message = "Content-Type: Text / Plain;" CRLF "" .padright (8, ') "Charset = /" mail.mailencoding.toString () "/" " CRLF; message =" Content-Transfer-Encoding: base64 " CRLF CRLF; if (mail.MailBody = null!) message = Convert.ToBase64String (mail.MailBody, 0, mail.MailBody.Length) CRLF CRL F CRLF "." CRLF;} else // HTML format {Message = "Content-Type: Multipart / Alertnative;" CRLF "" .padright (8, ') "Boundary" "= /" = ==== 003_Dragon310083331177 _ ===== / "" CRLF CRLF CRLF; Message = "this is a multi-part message in mime format" CRLF CRLF; Message = "

- ===== 003_dragon310083331177 _ ===== " CRLF; Message =" Content-type: text / html; " CRLF " ".padright (8, ') " charset = / " mail .MailEncoding.ToString () ToLower () "/" " CRLF; message =." Content-Transfer-Encoding: base64 " CRLF CRLF; if (mail.MailBody = null!) message = Convert.ToBase64String (mail .Mailbody, 0, mail.mailbody.length) CRLF CRLF; Message = "- ===== 003_Dragon310083331177 _ ===== -" CRLF CRLF CRLF "." CRLF;}} Else // With an attachment {// Processing data stringcollection attatchmentDataS = new stringcollection () {if (! File.exists (path)) {if (! File.exists (path)) {.. .. {ix. Seterror ("The specified attachment is not found;} else {// gets the byte stream fileInfo file = new fileinfo (path); filestream fs = new filestream (path, filemode.open, fileaccess.read); IF (fs.length>) {this.seEterror ("The size of the attachment beyond the maximum limit");} Byte [] file_b = new byte [(int) fs.length]; fs.read File_B, 0, File_B.LENGT h); fs.close (); string attatchmentmailstr = "Content-type: Application / OCTET-STREAM;" CRLF "" .padright (8, ') "Name =" "/"" file.name "/" " Crlf; attatchmentmailstr =" Content-Transfer-Encoding: base64 " crlf; attatchmentmailstr =" Content-disposition: attachment; " CRLF " "

.Padright (8, '') "filename =" "/"" file.name "/"" crlf crlf; attatchmentmailstr = convert.tobase64string (file_b, 0, file_b.length CRLF CRLF; AttatchMentDataS.Add (AttatchMAilStr);}} // Set mail information if (mail.mailtype == mailtypes.text) // text format {Message = "Content-type: multipart / mix;" CRLF "" .padright (8 , '') "Boundary = /" ===== 001_dragon320037612222 _ ===== / "" CRLF CRLF; Message = "this is a multi-part message in mime format." CRLF CRLF; Message = "- ======001_dragon3200376122222_ =====" CRLF; Message = "Content-Type: text / plain;" CRLF "" .padright (8, ') "charset = /" " mail.MailEncoding.ToString () ToLower () "/" " CRLF; message =." Content-Transfer-Encoding: base64 " CRLF CRLF; if (! mail.MailBody = null) message = Convert.ToBase64String (mail.mailbody, 0, mail.mailbody.length) CRLF; Foreach (String s in attatchmentdata) {message = "- ===== 001_dragon320037612222 _ =====" CRLF S CRLF CRLF; } Message = "- ===== 001_d Ragon320037612222_ ===== - " CRLF CRLF CRLF ". " CRLF;} else {Message =" Content-Type: Multipart / Mixed; " CRLF " ".padright (8, ''

) "boundary = /" ===== 001_dragon255511664284 _ ===== / "" CRLF CRLF; Message = "this is a multi-part message in mime format." CRLF CRLF; Message = "- - ===== 001_Dragon255511664284 _ ===== " CRLF; Message =" Content-type: text / html; " CRLF " ".padright (8, ') " charset = / "" mail. . MailEncoding.ToString () ToLower () "/" " CRLF; message =" Content-Transfer-Encoding: base64 " CRLF CRLF; if (mail.MailBody = null!) message = Convert.ToBase64String (mail. Mailbody, 0, mail.mailbody.Length) CRLF CRLF; for (int i = 0; i

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

New Post(0)