/ / =========================================================================================================================================================================================== ============ // 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 /// summary> public class mailsender {/// /// SMTP server domain name /// summary> public string server {get {return server } Set {ix (value! = Server) server = value;}}}} }.com.
/// /// SMTP server port [default is 25] /// summary> public int port {get {return port;} set {i (value! = port) port = value;}} private INT port = 25;
/// /// Username [If you need authentication] /// summary> public string username {get {return usrname;} set {if (value! = username) Username = value;}} Private string username = ""
/// /// password [If you need authentication] /// summary> public string password {get {return password;} set {if (value! = password) password = value;}} private String password = ""
/// /// sender address //// summary> public string from {get {return from;} set {i (value! = from) from = value;}} private string from = " "; /// /// recipient address /// summary> public string to {get {return to;} set {= to (value! = to) to = value;}} private string to = ""
/// /// sender name ////////////////////////////////////////////> "
/// /// recipient name /// summary> 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 /// summary> public string body {get {ket body;} set {= = body) body = value;}} private string body = ""
/// /// hypertext /// summary> public string htmlbody {get {return htmlbody;} set {if (value! = htmlbody) htmlbody = value;}} private string htmlbody = ""
/// /// is an HTML format message /// summary> public bool iShtml {get {returni {i (value! = iSHTML) iShtml = value;}} private bool iSHTML = FALSE;
/// /// language code [default GB2312] /// summary> public string LanguageEncoding {get {return languageEncoding;} set {if (! Value = languageEncoding) languageEncoding = value;}} private string LanguageEncoding = "gb2312"; /// /// mail code [default is 8bit] /// summary> public string mailencoding {get {return eNCoding;} set {if (value! = encoding) eNCoding = Value;}} private string encoding = "8bit";
/// /// Mail priority [default is 3] /// summary> public int priority {get {return priority;} set {i (value! = priority) priority = value;}} priority = value;}} private} INT priority = 3;
/// /// Annex [AttachmentInfo] /// summary> public IList Attachments {get {return attachments;} // set {if (! Value = attachments) attachments = value;}} private ArrayList attachments = new arraylist ();
/// /// Send mail /// summary> 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 param> 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 //// summary> /// stream from TCPClient param> //// Read characters return (networkStream NetStream) {string sp = null; Byte [] by = new byte [1024]; int size = netstream.read (by, 0, by.length); / / Read data stream if (size> 0) {sp = encoding.default.getstring (by); // Translate into string} Return sp;}
/// /// The command is issued and the return information is correct /// summary> /// from TCPClient stream param> /// Command param> /// correct status code param> /// Whether it correctly returns> 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 /// ////// Summary> /// string param> /// Base64 encoded string returns> 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 /// summary> public struct attachmentinfo {/// /// The file name of the attachment [If the path is input, automatically convert to file name] /// summary> public string filename {get {return filename;} set {filename = path.getFileName (value);}} private string filename
/// /// Attachment content [Composed of Base64 encoded bytes] /// summary> public string Bytes {get {returnTes;} set {if (value! = bytes) BYTES = Value;}
/// /// read attachment content from the stream and constructs /// summary> /// The file name of the attachment param> /// stream param> 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 /// summary> /// File name param> /// Annex [byte] param> public AttachmentInfo (String ifilename, Byte [] ibytes) {filename = path.getFileName (ifilename); BYTES = Convert.TOBASE64String (ibytes); // Translate into Base64 Codes}
/// /// From the file load and constructed /// summary> /// param> 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"));