C # implements the SMTP server, use the TCP command to implement, and the function is relatively perfect.

xiaoxiao2021-03-06  111

Using system; using system.net; using system.net.sockets; using system.collections;

Namespace Skydev.Web.mail {public enum mailformat {text, html}; public enum mailpriority {low = 1, NORMAL = 3, high = 5};

#REGON CLASS Mailattachments PUBLIC CLASS MAILATTACHMENTS {Private const Int maxattachmentnum = 10; private ilist_attachments

Public maiptachments () {_ttachments = new arraylist ();

Public string this [int index] {get {return (string) _attachments [index];}} ///

/// Add mail attachment /// /// Accessories' absolute path public void add (params string [] filepath) {if (filepath == null) {throw ("illegal attachment");} else {for (INT i = 0 ; i

///

// / Add an attachment, when the specified attachment does not exist, ignore the attachment without producing an exception. /// /// The absolute path of the attachment public void add (string filepath) {// is added when the attachment exists, otherwise ignore IF (System.IO .File.exists (filepath)) {if (_ttachments.count

Public void clear () // Clear all attachments {_attachments.clear ();

Public int count // Gets the number of attachments {Get {return_attachments.count;}}

} # EndRegion // end class mailattachments

#REGON Class MailMessage ///

///milMessage indicates a message that SMTP is to be sent. /// public class MailMessage {private const int MaxRecipientNum = 10; public MailMessage () {_Recipients = new ArrayList (); // recipient list _Attachments = new MailAttachments (); // Annex _BodyFormat = MailFormat. TEXT; / / The default mail format is text _Priority = mailpriority.Normal; _Charset = "GB2312";} /// /// Setting language code, the default setting is GB2312, if not required to be set "" /// public string charset {get {return_charset;} set {_charset = value;}}

Public string from {get {r _from;} set {_from = value;}}

Public string fromname {get {return_fromname;} set {_fromname = value;}} public string body {rary _body;} set {_body;} set {_body = value;

Public string subject {get {return _subject;} set {_subject = value;}}

Public mailattachments attachments {get {return_attachments;} set {_attachments = value;}}

Public mailpriority priority {get {return _priority;} set {_priority = value;}}

Public IList Recipients {Get {Return_Recipients;}} ///

/// Add a recipient address ////////////// Recipient's Email address public void addrecipients (String Recipient) {// Check if the email address meets the specification IF (_Recipients.count

Public void addrecipients (params string [] Recipient) {if (Recipient == null) {throw ("Recipient can't empty."));} else {for (int i = 0; i

public MailFormat BodyFormat {set {_BodyFormat = value;} get {return _BodyFormat;}} private string _From; // address of the sender private string _FromName; // the name of the sender private IList _Recipients; // recipient private MailAttachments _Attachments ; // accessories private string _Body; // content private string _Subject; // subject of private MailFormat _BodyFormat; // message format private string _Charset = "GB2312"; // character encoding format private MailPriority _Priority; // message priority} # EndRegion

#Region Class Smtpmail Public Class SmtpserverHelper {Private String CRLF = "/ R / N"; // Enter Return

///

/// Error message feedback /// private string errmsg;

///

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

///

/// NetWorkStream object /// Private networkStream NetworkStream;

///

/// server interaction record /// private string logs = "";

///

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

///

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

Public SMTPServerHelper () {smtpcodeadd (); // Initialization SMTPCode}

~ SMTPSERVERHELPER () {NetWorkStream.close (); tcpclient.close ();

///

/// 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);}

///

/// will decode Base64 string to normal string /// String private string base64decode (String) Str) {byte [] barray; barray = convert.frombase64string (str); return encoding.default.getstring (barray);} /// ///> File flow /// /// The absolute path of the attachment private string getStream (String filepath) {// Establish file stream object system.io.filestream filester = 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));

///

/// SMTP response code hash table /// private void smtpcodeadd () {// [RFC 821 4.2.1.] / * 4.2.2. Numeric Order List of Reply Codes

211 System status, or system help reply 214 Help message [Information on how to use the receiver or the meaning of a particular non-standard command; this reply is useful only to the human user] 220 Service ready 221 Service closing transmission channel 250 Requested mail action okay, completed 251 User not local; will forward to 354 Start mail input; end with 421 Service not available, closing transmission channel [. This may be a reply to any command the service knows it must shut down] 450 Requested mail action not taken if: mailbox unavailable [Eg, mailbox busy] 451 Requested action aborted: local error in processing 452 Requested action not taken: insufficient system storage 500 Syntax Error, Command Unrecognized [this May include Errors SuMMAND LINE TOON] 501 SYNTAX ERROR in Parameters or Arguments 502 Command Not IMPLEM ented 503 Bad sequence of commands 504 Command parameter not implemented 550 Requested action not taken: mailbox unavailable [Eg, mailbox not found, no access] 551 User not local; please try 552 Requested mail action aborted: exceeded storage allocation 553 Requested Action Not Taken: Mailbox Name Not ALLOWED [EG, Mailbox Syntax IncorRect] 554 Transaction Failed * /

Errcodeht.Add ("421", "Service is not ready, close transmission channel"); errcodeht.add ("432", "requires a password conversion"); errcodeht.add ("450", "required mail operation is not completed , Mailboxes are unavailable (for example, mailbox busy) "); errcodeht.add (" 451 "," abandon the required operation; error during processing "); errcodeht.add (" 452 "," system storage is insufficient, required operation Not executed "); errcodeht.add (" 454 "," Temporary authentication failed "); errcodeht.add (" 500 "," Mailbox 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 ("530", "need to authenticate"); errcodeht.add ("534", "Certification mechanism is too simple"); errcodeht.add ("538", "Current Request Certification Mechanism Requires"); errcodeht.Add ( "550", "The email operation requested is not completed, the mailbox is unavailable (for example, the mailbox is not found, or can not access)"); errcodeht.add ("551", "User Non-local, please try " ); Errcodeht.add ("552", "excess storage allocation, required operation is not executed"); errcodeht.add ("553", "mailbox name is unavailable, the required operation is not executed (such as mailbox format error)" ); Errcodeht.add ("554", "Transmission Failed"); / * 211 System Status, or System Help Reply 214 Help Message [Information On How To Use the receiver or the meaning of a particular non-standard Command; this reply Is Useful ONLY TO The Human User] 220 Service Ready 221 Service Closing Transmission Channel 250 Requested Mail Action Okay, Completed 251 User Not Local; Will Forward to 354 Start Mail Input; End with . * /

Rightcodeht.add ("220", "Service Ready"); RightCodeht.Add ("221", "Service Close Transfer Channel"); RightCodeht.Add ("235", "Verification Success"); RightCodeht.Add ("250 "," Required Mail Operation "); RightCodeht.Add (" 251 "," Non-local users, will forward to "); RightCodeht.Add (" 334 "," server response verification base64 string "); RightCodeht.Add (" 354 "," starting mail input, end "at . );}

///

/// 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 {networkStream.Write (WriteBuffer, 0, WriteBuffer.Length);} catch {errmsg = "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 = NetworkStream.read (Readput, 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.CRLF; 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 () == String.empty) {Return True;} {STRING RR = recvResponse (); if (RR == "false") {return false;} // check the return code, depending on [RFC 821] return code 3 digit code such as 220 string rrcode = r.substring (0, 3); if (RightCodeht [ RRCODE]! = Null) {RTURN TRUE;} else {if (errcodeht [rcode]! = Null) {errmsg = (rrcode errcodeht [rcode] .tostring ()); errmsg = crlf;} else {errmsg = rr; } Errmsg = errstr; return false;}}}}} /// /// interacts with the server, sends a set of commands and receives a response. ///

Private Bool Dialog (String [] str, string errstr) {for (int i = 0; i

Return True;}

// Connect the server private bool connect (STRING SMTPSERVER, INT port) {// Create TCP connection try {tcpclient = new TcpClient (SMTPSERVER, Port);} catch (exception e) {errmsg = e.toString (); Return False; NetWorkStream = tclient.getStream ();

// Verify that the network connection is correct if (rightcodeht [recristode (). Substring (0, 3)] == null) {errmsg = "Network connection failed"; return false;} return true;}

private string GetPriorityString (MailPriority mailPriority) {string priority = "Normal"; if (mailPriority == MailPriority.Low) {priority = "Low";} else if (mailPriority == MailPriority.High) {priority = "High";} Return priority;} ///

/// Send email, SMTP server does not require authentication /// /// /// /// /// public bool sendemail (String SMTPServer, Int port, mailmessage mailmessage) {Return Sendemail (SMTPSERVER, Port, False, "", "", MailMessage);

///

/// Send an email, the SMTP server requires authentication /// /// /// /// /// /// /// public bool SendEmail (string smtpServer, int port, string username, string password, MailMessage mailMessage) {return SendEmail (smtpServer, port, false, username, password, mailMessage);}

Private Bool Sendemail (String SMTPServer, INT Port, Bool Esmtp, String User, String Password, MailMessage MailMessage) {if (Connect (SMTPServer, Port) == false // The test connection server success Return False;

String priority = getPriorityString (MailMessage.Priority); BOOL HTML = (MailMessage.BodyFormat == MailFormat.html); string [] SendBuffer; string sendbuffers

// SMTP verification, now most of the SMTP server must authenticate if (esmtp) {sendbuffer = new string [4]; sendbuffer [0] = "EHLO" SMTPSERVER CRLF; SendBuffer [1] = "auth login" CRLF; sendbuffer [2] = base64encode (username) CRLF; sendbuffer [3] = base64encode (password) CRLF; if (! Dialog (SendBuffer, "SMTP server verification failed, check the username and password.") Return False } Else {// does not require identity authentication sendbuffrstr = "helo" SMTPSERVER CRLF; if (! Dialog (sendbufferstr, ")) Return False;} // sender address sendbuffrstr =" mail from: <" MailMessage.From ">" CRLF; if (! Dialog (SendBufferstr, "sender address error, or no empty")) Return False;

// Recipient Address SendBuffer = new string [MailMessage.Recipients.count]; for (int i = 0; i " CRLF;} if (! Dialog (sendbuffer, "The Recipient Address is incorrect")) Return False;

/ * Sendbuffer = new string [10]; for (int i = 0; i

Sendbuffer [i] = "RCPT TO: <" RecipientBCC [i] .tostring () "> CRLF;

}

IF (! Dialog (SendBuffer, "Portfeli Address incorrect")) Return False; * /

Sendbufferstr = "DATA" CRLF; if (! Dialog (SendBufferstr, ")) Return False;

// send a name SendBufferstr = "from:" MailMessage.FromName <" MailMessage.From "> CRLF;

//if(ReplyTo.trim () != "" // {// sendbufferstr = "reply-to:" replyto crlf; //}

// sendbufferstr = "TO:" TONAME "<" Recipient [0] "> CRLF; // At least there is a recipient IF (MailMessage.Recipients.count == 0) {Return False; } Else {sendbufferstr = "TO: =?" MailMessage.Charset.toupper () "? B?" Base64encode ((string) MailMessage.Recipients [0]) "? =" "<" ( String) MailMessage.Recipients [0] > " CRLF;} // sendbufferstr =" cc: "; // for (int i = 0; i ,"; //} // sendbufferstr = CRLF;

SendBufferstr = ((MailMessage.Subject == String.empty || MailMessage.Subject == NULL)? "Subject:": ((MailMessage.Charset == ")? (" Subject: " MailMessage.Subject) :( "Subject:" "=?" MailMessage.charset.toupper () "? B?" Base64Encode (MailMessage.Subject) "? =")) CRLF; SendBufferstr = "X-Priority:" priority CRLF; SendBufferstr = "X-MSMail-priority:" priority CRLF; SendBufferstr = "Importance:" priority CRLF; SendBufferstr = "X-Mailer: Lion.Web.Mail.SmtpMail Pubclass [cn]" CRLF; SendBufferstr = "MIME-Version: 1.0" CRLF; if (mailMessage.Attachments.Count = 0!) {SendBufferstr = "Content-Type: multipart / mixed;" CRLF; SendBufferstr = "boundary = /" = ==== " (html?" 001_dragon520636771063 _ ":" 001_dragon303406132050 _ ") " ===== / "" CRLF CRLF;}

IF (html) {if (MailMessage.attachments.count == 0) {sendbufferstr = "Content-type: multipart / alternative;" CRLF; // Content format and separator sendbufferstr = "boundary = /" == === 003_Dragon520636771063 _ ===== / "" CRLF CRLF; SendBufferstr = "this is a multi-part message in mime format." CRLF CRLF;} else {sendbufferstr = "this is a multi- Part Message In Mime Format. " CRLF CRLF; SendBufferstr =" - ===== 001_Dragon520636771063 _ ===== " CRLF; SendBufferstr =" Content-Type: Multipart / Alternative; " CRLF; / / Content format and separator sendbuffrstr = "boundary = /" ===== 003_Dragon520636771063 _ ===== / " CRLF CRLF;} sendbufferstr =" - ===== 003_Dragon520636771063 _ ==== = " CRLF; SendBufferstr =" Content-Type: text / plain; " CRLF; SendBufferstr = ((MailMessage.Charset ==")? ("Charset = /" ISO-8859-1 / "" " :( "Charset = /" " MailMessage.Charset.tolower () " / ")) CRLF; SendBufferstr =" Content-Transfer-Encoding: Base64 " CRLF CRLF; SendBufferstr = Base64Encode (" message content HTML format, select HTML View ") CRLF CRLF;

Sendbufferstr = "- ===== 003_dragon520636771063 _ =====" CRLF;

SendBufferstr = "Content-Type: Text / HTML;" CRLF; SendBufferstr = ((MailMessage.Charset == ")? (" Charset = / "ISO-8859-1 /"): ("charset = /" " mailMessage.Charset.ToLower () " / "")) CRLF; SendBufferstr = "Content-Transfer-Encoding: base64" CRLF CRLF; SendBufferstr = Base64Encode (mailMessage.Body) CRLF CRLF; SendBufferstr = "- ===== 003_dragon5206367771063 _ ===== -" CRLF;} else {if (MailMessage.attachments.count! = 0) {sendbufferstr = "- ===== 001_dragon303406132050 _ == === " CRLF;} SendBufferstr =" Content-type: text / plain; " CRLF; SendBufferstr = ((MailMessage.Charset ==")? ("Charset = /" ISO-8859-1 / "" ) :( "charset = /" " mailMessage.Charset.ToLower () " / "")) CRLF; SendBufferstr = "Content-Transfer-Encoding: base64" CRLF CRLF; SendBufferstr = Base64Encode (mailMessage.Body ) CRLF;} // sendbufferstr = "Content-Transfer-Encoding: Base64" CRLF;

IF (MailMessage.attachments.count! = 0) {for (int i = 0; i

Sendbufferstr = "quit" crlf; if (! Dialog (SendBufferstr, "Disconnected when the connection")) Return False;

NetWorkStream.close (); tcpclient.close (); return true;}} public class smtpmail {private static string _smtpserver;

///

/// format: SMTPACCOUNT: Password @ SMTPSERVERVERADDRESS
/ / / or: SMTPSERVERVERADDRESS
/// /// SMTPMAIL.SMTPSERVER = "User: 12345678@smtp.126. COM "; /// // or: /// SMTPMAIL.SMTPSERVER =" SMTP.126.com "; /// // or: /// SMTPMAIL.SMTPSERVER = SMTPSERVERHELPER.GETSMTPSERVER (" User "," 12345678 "," SMTP.126.com "); /// /// public static string smtpserver {set {_smtpserver = value;} get {return_smtpserver;}}

public static bool Send (MailMessage mailMessage, string username, string password) {SmtpServerHelper helper = new SmtpServerHelper (); return helper.SendEmail (_SmtpServer, 25, username, password, mailMessage);}

}

#ndregion} using system; using nunit.framework;

Namespace Skydev.Web.mail {///

/// TEST summary description. /// [TestFixTure] Public class testsmtpmail {// Install the test case, complete the initialization operation [setup] public void setup ()}

// end of the test the cleaning operation is completed [TearDown] public void TearDown () {} [Test] public void TestMailAttachments () {SkyDev.Web.Mail.MailAttachments attachments = new MailAttachments (); Assert.AreEqual (0, attachments.Count, "Initialization MailatTachments"); attachments.add ("c: //autoexec.bat"); assert.arequal (1, attachments.count, "increasing attachment (attachment does exist)"); attachments.add ("C: / /autoexec.dat.txt "); assert.arequal (1, attachments.count," increasing attachment (attachment does not exist) "); attachments.clear (); assert.arequal (0, attachments.count," Clear attachment " }

[Test] public void TestMailMessage () {MailMessage message = new MailMessage (); Assert.AreEqual (0, message.Attachments.Count, "initialization MailAttachments"); Assert.AreEqual (MailFormat.Text, message.BodyFormat, "Message Format "); Assert.arequal (" GB2312 ", Message.Charset," default character set ");} [TEST] public void testsendmail () {smtpmail.smtpserver =" smtp.126.com "; mailmessage mail = new MailMessage (); mail.from = "qs1976@126.com"; mail.fromname = "Zeng Qingsong"; mail.addrecipients ("qs1976@126.com"); mail.subject = "Topic: Test Mail"; Mail .Bodyformat = mailformat.text; mail.body = "Test content."; Mail.attachments.add ("c: //test.txt"); SMTPMAIL.SEND (Mail, "," ""); // Please fill in your own test mail account}}}

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

New Post(0)