C # - mailsender mail sending component source code (support ESMTP, accessory)

zhaozj2021-02-16  52

/ / =========================================================================================================================================================================================== ============ // file: mailsender.cs // message send component // support ESMTP, multi-attachment / / ================= ===================================================

Namespace jcpersonal.utility {using system; using system.net.sockets; using system.io; using system.text;

///

///mail sender /// public class mailsender {/// /// SMTP server domain name /// public string server {get {return server } Set {ix (value! = Server) server = value;}}}} }.com.

///

/// SMTP server port [default is 25] /// public int port {get {return port;} set {i (value! = port) port = value;}} private INT port = 25;

///

/// Username [If you need authentication] /// public string username {get {return usrname;} set {if (value! = username) Username = value;}} Private string username = ""

///

/// password [If you need authentication] /// public string password {get {return password;} set {if (value! = password) password = value;}} private String password = ""

///

/// sender address //// public string from {get {return from;} set {i (value! = from) from = value;}} private string from = " "; /// /// recipient address /// public string to {get {return to;} set {= to (value! = to) to = value;}} private string to = ""

///

/// sender name ////////////////////////////////////////////> "

///

/// recipient name /// public string toname {get {return toname;} set {if (value! = toname) Toname = value;}} prince string toname = " "

///

/// message topic //////////////////////ww (value! = Subject) subject = value;}} private string subject = "" ;

///

/// message body /// public string body {get {ket body;} set {= = body) body = value;}} private string body = ""

///

/// hypertext /// public string htmlbody {get {return htmlbody;} set {if (value! = htmlbody) htmlbody = value;}} private string htmlbody = ""

///

/// is an HTML format message /// public bool iShtml {get {returni {i (value! = iSHTML) iShtml = value;}} private bool iSHTML = FALSE;

///

/// language code [default GB2312] /// public string LanguageEncoding {get {return languageEncoding;} set {if (! Value = languageEncoding) languageEncoding = value;}} private string LanguageEncoding = "gb2312"; /// /// mail code [default is 8bit] /// public string mailencoding {get {return eNCoding;} set {if (value! = encoding) eNCoding = Value;}} private string encoding = "8bit";

///

/// Mail priority [default is 3] /// public int priority {get {return priority;} set {i (value! = priority) priority = value;}} priority = value;}} private} INT priority = 3;

///

/// Annex [AttachmentInfo] /// public IList Attachments {get {return attachments;} // set {if (! Value = attachments) attachments = value;}} private ArrayList attachments = new arraylist ();

///

/// Send mail /// public void sendmail () {// Create a TCPClient object, and establish a connection TCPCLIENT TCP = NULL; try {TCP = New TcpClient (Server, Port); } CatCH (Exception) {throw new exception ("Unable to connect server");

ReadString (TCP.GetStream ()); // Get connection information

// Start Server Certification // If the status code is 250, the operation is successful if (! Command (tcp.getStream (), "Ehlo LocalHost", "250") "" Land Drape Failure ");

IF (username! = ") {// requires authentication if (! Command (tcp.getStream ()," auth login "," 334 ")) throw new exception (" Authentication phase failed "); string nameb64 = Tobase64 (UserName); convert UserName to Base64 code if (! Command (tcp.getStream (), Nameb64, "334")) throw new exception ("Authentication phase failed"); string passb64 = tobase64 ( Password); // Convert Password to Base64 code if (! Command (TCP.getStream (), Passb64, "235")) throw new exception ("Authentication phase failed");} // Preparing to send WRITESTRING TCP.GetStream (), "Mail from:" from); WritestRing (TCP.GetStream (), "RCPT TO:" TO); WritestRing (TCP.getStream (), "DATA");

// Send the mail head WritestRing (TCP.getStream (), "Date:" DateTime.Now); // Time WriteString (tcp.getStream (), "from:" fromname "<" from ">" ); // sender WritestRing (TCP.getStream (), "Subject:" Subject); // Topic WritestRing (TCP.GetStream (), "TO:" Toname "< to "> " ); // recipient

// Mail format WRITESTRING (TCP.GetStream (), "Content-Type: Multipart / Mixed; bitchary = /" unique-boundary-1 / "); WritestRing (TCP.getStream ()," reply-to: " From); // Reply Address Writestring (TCP.getStream (), "X-Priority:" priority); // Priority WRITESTRING (TCP.getStream (), "MIME-VERSION: 1.0"); // Mime version

// Data ID, random // WriteString (TCP.getStream (), "Message-ID:" DateTime.now.tofiletime () "@ security.com"); WritestRing (TCP.GetStream (), "Content- Transfer-encoding: " Encoding); // Content Code WriteString (TCP.getStream ()," X-MAILER: JCPERSONAL.UTILITY.MAILSENDER "); // Mail sender WritestRing (TCP.getStream ()," ") Writestring (TCP.getStream (), Tobase64 ("This Is A Multi-Part Message In Mime Format."); WriteString (TCP.getStream (), "")

/ / Start from this to the separation input WriteString (TCP.GetStream (), "--unique-Boundary-1");

/ / Define the second separator WRITESTRING (TCP.GETSTREAM (), "Content-Type: Multipart / Alternative; Boundary = /" Unique-Boundary-2 / "); WriteString (TCP.getStream (), "" "

IF (! iSHTML) {// Text Information WritestRing (TCP.GetStream (), "--unique-Boundary-2"); WritestRing (TCP.GetStream (), "Content-Type: Text / Plain; Charset =" LanguageEncoding; WritestRing (TCP.getStream (), "Content-Transfer-Encoding:" Encoding); WritestRing (TCP.getStream (), ""); WritestRing (TCP.getStream (), body); WritestString (TCP. GetStream (), ""); // After writing, you will write as empty information, segment WRITESTRING (TCP.GetStream (), "--unique-boundary-2 -"); // Separator end Symbols, behind the tails - WriteString (TCP.getStream (), "");} else {// HTML information WriteString (TCP.GetStream (), "--unique-Boundary-2"); WritestString (TCP. GetStream (), "Content-Type: Text / HTML; Charset =" LanguageEncoding); Writestring (TCP.GetStream (), "Content-Transfer-Encoding:" Encoding); WritestString (TCP.getStream (), "" ); Writestring (TCP.getStream (), HTMLBody; WritestRing (TCP.GetStream (), ""); Writestring (TCP.GetStream (), "--unique-Boundary-2 -"); // Deridiator The end symbol, there are more than the tail - WriteString (TCP.getStream (), "");

// Send an attachment // Take a loop for the file list for (int i = 0; i

// Close the connection tcp.close ();

///

/ /////////////////////////////////////////////////// Write character protected void writString (networkStream NetStream, String Str) {str = STR " / R / N "; // joining a wrapper

// Translate the command line to Byte [] Byte [] bwrite = Encoding.GeteEncoding .getBytes (Str.ToChararray ());

// Since the size of each write is limited, then we will set the length of the data written to 75 bytes, once the command length exceeds 75, step by step. INT start = 0; intlength = bWrite.Length; int point = 75; int count = size; try {i (length> 75) {// Data page IF ((length / size) * Size < Length) Page = Length / Size 1; Else Page = Length / size; for (INT i = 0; i /// Read characters from the stream //// /// stream from TCPClient //// Read characters 0) {sp = encoding.default.getstring (by); // Translate into string} Return sp;}

///

/// The command is issued and the return information is correct /// /// from TCPClient stream /// Command /// correct status code /// Whether it correctly Protected Bool Command (NetworkStream NetStream, String Command, String State) {string sp = null; bool success = false; try {writestRing (netstream, command); // Write command sp = readstring (netstream); // Accept return information if (sp.indexof (state)! = -1) // determine if the status code is correct acche;} catch (exception) {// ignore the error} Return Success;} /// /// string is Base64 /// /// string /// Base64 encoded string protected string tobase64 (string str) {try {byte [] by = encoding.default .Getbytes (Str.Tochararray ()); str = convert.tobase64string (by);} catch (exception) {// ignore error} Return Str;}

///

/// attachment information /// public struct attachmentinfo {/// /// The file name of the attachment [If the path is input, automatically convert to file name] /// public string filename {get {return filename;} set {filename = path.getFileName (value);}} private string filename

///

/// Attachment content [Composed of Base64 encoded bytes] /// public string Bytes {get {returnTes;} set {if (value! = bytes) BYTES = Value;}

///

/// read attachment content from the stream and constructs /// /// The file name of the attachment /// stream public attachmentinfo (string ifilename, stream stream) {filename = path.getFileName (ifilename); Byte [] by = new byte [strength.length]; stream.read (By, 0, (int) stream.length); // Read file content // format conversion Bytes = convert.tobase64String (by); // Translate into Base64 encoding} /// ///> Follow the given byte construction Attachment /// /// File name /// Annex [byte] public AttachmentInfo (String ifilename, Byte [] ibytes) {filename = path.getFileName (ifilename); BYTES = Convert.TOBASE64String (ibytes); // Translate into Base64 Codes}

///

/// From the file load and constructed /// /// public attachmentInfo (String Path) {filename = path.getFileName ( PATH); filestream file = new filestream (path, filemode.open); byte [] by = new byte; file.read (by, 0, (int) file.length; // read file Content // Format Conversion Bytes = Convert.TOBASE64String (by); // Translate into Base64 Code File.Close ();}}}}}

// Use:

Mailsender ms = new mailsender (); ms.From = "jovenc@tom.com"; ms.to = "jovenc@citiz.net"; ms.subject = "subject"; ms.body = "body text"; ms .Username = "########"; // How can I tell you? Ms.password = "********"; // How can I tell you MS.Server = "SMTP. Tom.com ";

Ms.attachments.add (New Mailsender.attachmentInfo (@ "d: /test.txt"));

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

New Post(0)