Using system;
Using system.text;
Using system.io;
Using system.net;
Using system.net.sockets;
Using system.collections;
Namespace lion_office.data.library.mailclass
{
/ *
-------------------------------------------------- ---------------
* /
Public Class Esmtpmail
{
Private string enter = "/ r / n";
///
/// Set the language code, the default setting is GB2312, if it is not necessary to set it ""
/// summary>
Public string charSet = "GB2312";
///
/// sender address
/// summary>
Public String from = ""
///
/// send a name
/// summary>
Public String fromName = ""
///
/ / / Reply to the email address
/// summary>
// public string replyto = ""
///
/// The recipient's name
/// summary>
Public String RecipientName = ""
///
/// Recipient list
/// summary>
Private hashtable recipient = new hashtable ();
///
/// signal server domain name
/// summary>
Private string mailserver = ""
///
/// mail server port number
/// summary>
Private Int mailserverport = 25;
///
/// SMTP authentication username
/// summary>
Private string username = ""
///
/// SMTP authentication password
/// summary>
Private string password = ""
///
/ /: Do you need SMTP verification
/// summary>
Private bool esmtp = false;
///
/ /: HTML mail
/// summary>
Public Bool HTML = FALSE;
///
/// mail attachment list
/// summary>
Private system.collections.Arraylist attachments;
///
/// The mail is prioritized, which can be set to "High", "Normal", "Low" or "1", "3", "5" /// summary>
Private string priority = "normal";
///
/// Email Subject
/// summary>
Public String Subject = ""
///
/// mail body
/// summary>
Public String Body = ""
///
/// Recipient quantity
/// summary>
PRIVATE INT RecipientNum = 0;
///
/// Maximum number of recipients
/// summary>
Private int RecipientMaxNum = 1;
///
/// Double transfer number
/// summary>
// private int recipientbcnum = 0;
///
/// Error message feedback
/// summary>
Private string errmsg;
///
/// TcpClient object for connecting the server
/// summary>
Private TCPClient TC;
///
/// NetWorkStream object
/// summary>
Private netstream ns;
///
/// SMTP error code hash table
/// summary>
Private hashtable errcodeht = new hashtable ();
///
/// SMTP correct code hash table
/// summary>
Private hashtable rightcodeht = new hashtable ();
Public esmtpmail ()
{
Attachments = new system.collections.ArrayList ();
}
///
/// mail server domain name and verification information
///-shaped as: "User: pass@www.server.com: 25", you can also save the subsistence information. Such as "User: Pass@www.server.com" or "www.server.com"
/// summary>
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
/// summary>
Public Int Maildomainport
{
set
{
MailServerport = Value;
}
}
///
/// SMTP authentication username
/// summary>
Public String MailServerUserName
{
set
{
Value.trim ()! = "")
{
Username = value.trim ();
ESMTP = TRUE;
}
Else
{
Username = "";
ESMTP = FALSE;
}
}
}
///
/// SMTP authentication password
/// summary>
Public String MailServerPassword
{
set
{
Password = Value;
}
}
///
/// The message is prioritized, which can be set to "High", "Normal", "Low" or "1", "3", "5"
/// summary>
Public String Priority
{
set
{
Switch (Value.tolower ())
{
Case "high":
Priority = "high";
Break;
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;
}
}
}
///
/// Error message feedback
/// summary>
Public String ErrorMessage
{
get
{
Return errmsg;
}
}
///
/// server interaction record /// summary>
Private string logs = "";
///
/// server interactive record, 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 the reason as soon as possible.
/// summary>
Public String logs
{
get
{
Return Logs;
}
}
///
/// SMTP response code hash table
/// summary>
Private void smtpcodeadd ()
{
Errcodeht.Add ("500", "Email 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 ("421", "Service is not ready, shut down the transport channel");
Errcodeht.add ("450", "requested by mail operations, mailboxes are unavailable (for example, mailbox busy)");
Errcodeht.Add ("550", "requested by mail operations, mailboxes are unavailable (for example, mailboxes are not found, or irresisible)");
Errcodeht.Add ("451", "Abandoning the required operation; error during processing");
Errcodeht.Add ("551", "User is 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 is not performed");
Errcodeht.Add ("553", "mail address is not available, the required operation is not executed (such as a mailbox format error)");
Errcodeht.Add ("432", "requires a password conversion");
Errcodeht.Add ("534", "certification mechanism is too simple");
Errcodeht.Add ("538", "The currently requested authentication mechanism needs to be encrypted);
Errcodeht.Add ("454", "Temporary Certification Failure");
Errcodeht.Add ("530", "Requires Certification");
Rightcodeht.Add ("220", "Service Ready");
Rightcodeht.Add ("250", "Required Mail Operation");
Rightcodeht.add ("251", "users are non-local, will forward to
Rightcodeht.Add ("354", "Start the mail input, end" in
Rightcodeht.Add ("334", "Server Response Verification Base64 String");
Rightcodeht.Add ("235", "Verification Success");
}
///
/// Encourse the string to base64 string
/// summary>
/// String param> to encode param>
Private string base64encode (String STR)
{
Byte [] barray;
Barray = encoding.default.getbytes (STR);
Return Convert.TOBASE64STRING (BARRY);
}
///
// / Decoding the base64 string as a normal string
/// summary>
/// String param> to decode param>
Private String Base64Decode (String STR)
{
Byte [] barray;
Barray = Convert.FromBase64String (STR);
Return encoding.default.getstring (barray);
}
///
///> File flow of upload attachments
/// summary>
/// The absolute path of the attachment param>
Private string getStream (String filepath)
{
/ / Establish a file stream 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));
}
///
/// Add a mail attachment
/// summary>
/// Accessories absolute path param>
Public void addattachment (String Path)
{
Attachments.add (path);
}
///
/// Add a recipient
/// summary>
/// Recipient address param>
Public Bool AddRecipient (String STR)
{
Str = str.trim ();
IF (str == null || Str == "|| str.indexof (" @ ") == - 1)
Return True;
IF (RecipientNum Recipient.add (RecipientNum, STR); Recipientnum ; Return True; } Else { Errmsg = "The recipient is too much"; Return False; } } /// /// Maximum number of recipients /// summary> Public int RecipientMaxNum { set { RecipientMaxnum = value; } } /// /// Add a set of recipients (not more than RecipientMaxNum), parameter is a string array /// summary> /// Save the string array of recipient addresses (no more than RecipientMaxNum) param> Public Bool AddRecipient (String [] STR) { For (int i = 0; i { IF (! AddRecipient (STR [i])) { Return False; } } Return True; } /// /// Send the SMTP command /// summary> Private bool sendcommand (String Str) { BYTE [] WriteBuffer; IF (str.trim () == "" " { 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 /// summary> Private string recvresponse () { Int streemsize; String returnvalue = ""; 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; Return ReturnValue; } } /// /// Interaction with the server, send a command and receive a response. /// summary> /// A command to send param> /// If the error is required, the information you want to feedback param> Private bool dialog (String Str, String Errstr) { IF (str.trim () == "" " { Return True; } SendCommand (STR)) { String rr = recvresponse (); IF (rr == "false") { Return False; } Str.Substring (0, 3); IF (RIGHTCODEHT [RRCODE]! = NULL) { Return True; } Else { IF (errcodeht [rrcode]! = null) { Errmsg = (rrcode errcodeht [rcode] .tostring ()); Errmsg = Enter; } Else { Errmsg = RR; } Errmsg = Errstr; Return False; } } Else { Return False; } } /// /// Interaction with the server, send a set of commands and receive a response. /// summary> Private bool dialog (str, str, string errstr) { For (int i = 0; i { IF (! Dialog (STR [I], "))) { Errmsg = Enter; Errmsg = Errstr; Return False; } } Return True; } Private bool sendemail () { //Connect 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 [Recvresponse (). Substring (0, 3)] == NULL) { Errmsg = "Network connection failed"; Return False; } String [] sendbuffer; String sendbufferstr; / / SMTP verification IF (ESMTP) { Sendbuffer = new string [4]; Sendbuffer [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 can't be empty"))) Return False; // Sendbuffer = new string [RecipientMaxNum]; For (int i = 0; i { Sendbuffer [I] = "RCPT TO: <" Recipient [i] .tostring () "> Enter; } IF (! Dialog (SendBuffer, "Incomplete Recipient Address is incorrect)))))) Return False; SendBufferstr = "DATA" Enter; IF (! Dialog (SendBufferstr, "))) Return False; Sendbufferstr = "from:" fromname "<" from "> enter; SendBufferstr = "TO: =?" "?" "<" " "? = " " "? =" "<" "? =" " Enter; SendBufferstr = "CC:"; For (int i = 0; i { SendBufferstr = Recipient [i] .tostring () "<" Recipient [i] .tostring () ">," } SendBufferstr = Enter; IF (charset == "") { SendBufferstr = "Subject:" Subject Enter; } Else { SendBufferstr = "Subject:" "=?" "? B?" Base64Encode (Subject) "? =" ENTER; } SendBufferstr = "X-Priority:" Priority Enter; Sendbufferstr = "x-msmail-priority:" priority enter; SendBufferstr = "Importance:" Priority Enter; SendBufferstr = "x-mailer: huolx.pubclass" enter; sendbufferstr = "MIME-VERSION: 1.0" ENTER; SendBufferstr = "Content-Type: Multipart / Mixed;" Enter; // Content format and separator SendBufferstr = "Boundary = /" ---- = _ nextpart_000_00d6_01c29593.aab31770 / "" enter; Sendbufferstr = "------ = _ nextpart_000_00d6_01c29593.aab31770" enter; IF (HTML) { SendBufferstr = "Content-Type: Text / HTML;" Enter; } Else { SendBufferstr = "Content-Type: Text / Plain;" Enter; } IF (charset == "") { SendBufferstr = "Charset = /" ISO-8859-1 / "" Enter; } Else { SendBufferstr = "charset = /" " " / " enter; } // sendbufferstr = "Content-Transfer-Encoding: Base64" ENTER; SendBufferstr = "Content-Transfer-Encoding: Base64" ENTER ENTER; SendBufferstr = Base64Encode (Body) Enter; IF (attachments.count! = 0) { FOREACH (String FilePath in attachments) { Sendbufferstr = "------ = _ nextpart_000_00d6_01c29593.aab31770" enter; SendBufferstr = "Content-Type: Application / OcTet-stream" Enter; SendBufferstr = "name = /" =? " "? " Base64encode (filepath.lastindexof (" // ") 1)) "? = / "" enter; SendBufferstr = "Content-Transfer-Encoding: Base64" Enter; SendBufferstr = "Content-Disposition: attachment;" Enter; Sendbufferstr = "filename = /" =? " " TPATH.SUBSTRING ("//") 1)) "? = /" " 1)) "? = / "" ENTER ENTER; SendBufferstr = GetStream (FilePath) ENTER ENTER; } } SendBufferstr = "------ = _ nextpart_000_00d6_01c29593.aab31770 -" ENTER ENTER; SendBufferstr = Enter "." Enter; IF (! Dialog (SendBufferstr, "Error Letter Information")) Return False; Sendbufferstr = "quit" enter; IF (! Dialog (SendBufferstr, "Disconnects"))))))) Return False; ns.close (); Tc.close (); Return True; } /// /// Send an email method, all parameters are set by attribute. /// summary> Public bool send () { IF (Recipient.count == 0) { Errmsg = "The recipient list cannot be empty"; Return False; } IF (MailServer.trim () == "") { Errmsg = "Must specified SMTP Server"; Return False; } Return sendemail (); } /// /// Send an email method /// summary> /// SMTP server information, such as "UserName: Password@www.smtpserver.com: 25", you can also remove some times, such as "www.smtpserver.com" param> Public Bool Send (String SMTPServer) { Maildomain = SMTPSERVER; Return Send (); } /// /// Send an email method /// summary> /// SMTP server information, such as "UserName: Password@www.smtpserver.com: 25", you can also remove some times, such as "www.smtpserver.com" param> /// sender mail address param> /// sender name param> /// Recipient address param> /// Recipient Name param> /// Whether HTML mail param> /// Mail Topic param> /// Mail body param> Public Bool Send (String SMTPServer, String from, String ", 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 (); } } }