A very good Mail Class

xiaoxiao2021-03-06  18

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 ""

///

Public string charSet = "GB2312";

///

/// sender address

///

Public String from = ""

///

/// send a name

///

Public String fromName = ""

///

/ / / Reply to the email address

///

// public string replyto = ""

///

/// The recipient's name

///

Public String RecipientName = ""

///

/// Recipient list

///

Private hashtable recipient = new hashtable ();

///

/// signal server domain name

///

Private string mailserver = ""

///

/// mail server port number

///

Private Int mailserverport = 25;

///

/// SMTP authentication username

///

Private string username = ""

///

/// SMTP authentication password

///

Private string password = ""

///

/ /: Do you need SMTP verification

///

Private bool esmtp = false;

///

/ /: HTML mail

///

Public Bool HTML = FALSE;

///

/// mail attachment list

///

Private system.collections.Arraylist attachments;

///

/// The mail is prioritized, which can be set to "High", "Normal", "Low" or "1", "3", "5" ///

Private string priority = "normal";

///

/// Email Subject

///

Public String Subject = ""

///

/// mail body

///

Public String Body = ""

///

/// Recipient quantity

///

PRIVATE INT RecipientNum = 0;

///

/// Maximum number of recipients

///

Private int RecipientMaxNum = 1;

///

/// Double transfer number

///

// private int recipientbcnum = 0;

///

/// Error message feedback

///

Private string errmsg;

///

/// TcpClient object for connecting the server

///

Private TCPClient TC;

///

/// NetWorkStream object

///

Private netstream ns;

///

/// SMTP error code hash table

///

Private hashtable errcodeht = new hashtable ();

///

/// SMTP correct code hash table

///

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"

///

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

///

Public Int Maildomainport

{

set

{

MailServerport = Value;

}

}

///

/// SMTP authentication username

///

Public String MailServerUserName

{

set

{

Value.trim ()! = "")

{

Username = value.trim ();

ESMTP = TRUE;

}

Else

{

Username = "";

ESMTP = FALSE;

}

}

}

///

/// SMTP authentication password

///

Public String MailServerPassword

{

set

{

Password = Value;

}

}

///

/// The message is prioritized, which can be set to "High", "Normal", "Low" or "1", "3", "5"

///

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

///

Public String ErrorMessage

{

get

{

Return errmsg;

}

}

///

/// server interaction record ///

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.

///

Public String logs

{

get

{

Return Logs;

}

}

///

/// SMTP response code hash table

///

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 (" 221 "," Service Turn Transfer Channel ");

Rightcodeht.Add ("334", "Server Response Verification Base64 String");

Rightcodeht.Add ("235", "Verification Success");

}

///

/// Encourse the string to base64 string

///

/// String to encode

Private string base64encode (String STR)

{

Byte [] barray;

Barray = encoding.default.getbytes (STR);

Return Convert.TOBASE64STRING (BARRY);

}

///

// / Decoding the base64 string as a normal string

///

/// String to decode

Private String Base64Decode (String STR)

{

Byte [] barray;

Barray = Convert.FromBase64String (STR);

Return encoding.default.getstring (barray);

}

///

///> File flow of upload attachments

///

/// The absolute path of the attachment

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

///

/// Accessories absolute path

Public void addattachment (String Path)

{

Attachments.add (path);

}

///

/// Add a recipient

///

/// Recipient address

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

///

Public int RecipientMaxNum

{

set

{

RecipientMaxnum = value;

}

}

///

/// Add a set of recipients (not more than RecipientMaxNum), parameter is a string array

///

/// Save the string array of recipient addresses (no more than RecipientMaxNum)

Public Bool AddRecipient (String [] STR)

{

For (int i = 0; i

{

IF (! AddRecipient (STR [i]))

{

Return False;

}

}

Return True;

}

///

/// Send the SMTP command

///

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

///

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.

///

/// A command to send

/// If the error is required, the information you want to feedback

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.

///

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.

///

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

///

/// SMTP server information, such as "UserName: Password@www.smtpserver.com: 25", you can also remove some times, such as "www.smtpserver.com"

Public Bool Send (String SMTPServer)

{

Maildomain = SMTPSERVER;

Return Send ();

}

///

/// Send an email method

///

/// SMTP server information, such as "UserName: Password@www.smtpserver.com: 25", you can also remove some times, such as "www.smtpserver.com"

/// sender mail address

/// sender name

/// Recipient address /// Recipient Name

/// Whether HTML mail

/// Mail Topic

/// Mail body

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 ();

}

}

}

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

New Post(0)