Add a small feature to OpenPOP.Net, monitor data traffic when collecting emails!

xiaoxiao2021-03-06  41

/ * Recently wrote an automatic mail robot, it turned out to start lazy "" COM component Jmail: "Package JMail 4.4 POP3 is .NET component (.dll assembly), implement" mail (attachment) arrive ", etc. "Events"! "Later, I met OpenPop.Net. I am very empathless, then we will fall in love, then I will repair her: add a small function (red font code part), can be used to collect mail Monitor data traffic! Old rules: My code is casual to any. CSC can test in any .cs file! (The structure is not good, the purpose is convenient for test code) * /// OpenPop.NetNamespace openpop.mimeParser {us System; using system.io; using system.text.regularexpressions; using system.collections; using system.global;

///

/// summary description for attachment. /// public class attachment: iComparable {#Region Member Variables

private string _contentType = null; private string _contentCharset = null; private string _contentFormat = null; private string _contentTransferEncoding = null; private string _contentDescription = null; private string _contentDisposition = null; private string _contentFileName = ""; private string _defaultFileName = "body. htm "; private string _defaultFileName2 =" body * .htm "; private string _defaultReportFileName =" report.htm "; private string _defaultMIMEFileName =" body.eml "; private string _defaultMSTNEFFileName =" winmail.dat "; private string _contentID = null; Private long_ContentLength = 0; private string _rawattachment = null; private bool _inbytes = false; private bote [] _rawbytes = null;

#ndregion

#Region Properties

///

/// raw attachment content bytes /// public byte [] rawbytes {get {return _rawbytes;} set {_rawbytes = value;}}

///

/// WHETHER ATTACHMENT IN BYTES /// public bool inbytes {get {return _inbytes;} set {_inbytes = value;}} /// /// content length /// public long constlength {get {return_contentLength;}}

///

/// verify the attachment WHETER IT IT IS A Real attachment or not /// /// this is so far not comprehensive and needs more work to finish public bool NotAttachment {get {/ * if (_contentDisposition == null || _contentType == null) return true; else return (_contentDisposition.IndexOf ( "attachment") == - 1 && _contentType.IndexOf ( "text / plain")! = -1); * / / * if (_ContentType == null) Return true; else return (_ContentFileName! = "); * / If ((_ContentType == Null || _ContentFileName ==" ") && _ContentId == NULL) /////contenttype.tolower().indexof("text/") !=-1) Return True; Else Return False;

}

///

/// Content Format /// public string contentformat {get {returnTFormat;}}

///

/// Content Charset /// public string contentcharset {get {return_contentcharset;}}

///

/// default file name /// public string defaultFileName {get {return_defaultfilename;} set {_defaultfilename = value;}}

///

/// default file name 2 /// public string DefaultFileName2 {get {return _defaultFileName2;} set {_defaultFileName2 = value;}} /// /// default report file Name /// public string defaultReportFileName {get {return _defaultreportfilename;} set {_defaultreportFileName = value;}}

///

/// default mime file name /// public string defaultmimefilename {get {return_defaultmimefilename;} set {_defaultmimefilename = value;}}

///

/// Content Type /// public string contenttype {get {return_contenttype;}}

///

/// Content Transfer Encoding /// public string contentTransferencoding {get {return _contentTransferenCoding;}}

///

/// content description /// public string contentdescription {get {return_contentdescription;}}

///

///content file name /// public string contentFileName {get {return_contentFilename;} set {_contentFileName = value;}}

///

/// Content Disposition /// public string contentdisposition {get {return_contentdisposition;}}

///

/// Content ID /// public string contentId {get {returnTentId;}}

///

/// raw attachment /// public string rawattachment {get {return_rawattachment;}}

///

/// decoded attachment in bytes /// public byte [] decodedattachment {get {return decodedasbytes ();}} #ENDREGION

///

/// Release All Objects /// ~ attachment () {_rawbytes = null; _Rawattachment = null;}

///

/// new attachment /// /// attachment bytes content /// file length < / param> /// file name /// content type public Attachment (byte [] bytAttachment, long lngFileLength, string strFileName String strcontenttype) {_inbytes = true; _rawbytes = bytattachment; _contentLength = lngfilelength; _contentFileName = strfilename; _CONTENTTYPE = STRCONTTYPE

///

/// new attachment /// /// attachment bytes content /// File Name < / param> /// content type public Attachment (byte [] bytAttachment, string strFileName, string strContentType) {_inBytes = true; _rawBytes = bytAttachment; _contentLength = bytAttachment.Length; _contentFileName = strfilename; _CONTENTTYPE = STRCONTENTTTYPE;

///

/// new attachment /// /// attachment content /// whether only parse the header or not public Attachment (string strAttachment, string strContentType, bool blnParseHeader) {if {_contentFileName = _defaultMSTNEFFileName (blnParseHeader!); _contentType = strContentType } This.newattachment (Strattachment, BLNPARSEHEADER);} /// /// new attachment /// /// Attachment Content public attachment ( String strattachment) {this.newattachment (strattachment, true);}

///

/// Create attachment /// /// Raw attachment text /// Parse header < / Param> Private void newattachment (String Strattachment, Bool BLNPARSEHEADER) {_INBYTES = false

IF (Strattachment == Null) Throw new ArgumentnullException ("strattachment");

StringReader srreader = new stringReader (Strattachment);

if (blnParseHeader) {string strLine = srReader.ReadLine (); while (Utility.IsNotNullTextEx (strLine)) {ParseHeader (srReader, ref strLine); if (Utility.IsOrNullTextEx (strLine)) break; else strLine = srReader.ReadLine ( }}

THIS._RAWATTACHMENT = SRREADER.ReadToend (); _ContentLength = this._rawattachment.length;}

///

/// Parse header fields and set member variables /// /// String reader /// header line private void ParseHeader (StringReader srReader, ref string strLine) {string [] array = Utility.GetHeadersValue (strLine); //Regex.Split(strLine, ":"); string [] values ​​= Regex . Split (array [1], ";"); // array [1] .split (';'); string strret = null;

Switch (array [0] .toupper ()) {copy "content-type": if (VALUES.LENGTH> 0) _ContentType = VALUES [0] .trim (); if (VALUES.LENGTH> 1) {_ContentCharset = Utility .GetquotedValue (Values ​​[1], "=", "charset");} if (Values.Length> 2) {_ContentFormat = Utility.getQuoteDValue (Values ​​[2], "=", "Format");} _contentFileName = Utility.ParseFileName (strLine); if (_contentFileName == "") {strRet = srReader.ReadLine (); if (strRet == "") {strLine = ""; break;} _contentFileName = Utility.ParseFileName (strLine); if (_contentFileName == "") ParseHeader (srReader, ref strRet);} break; case "CONTENT-TRANSFER-ENCODING": _contentTransferEncoding = Utility.SplitOnSemiColon (array [1]) [0] .Trim (); break; case "Content-description": _ContentDescription = uTility.DecodeExt (utility.splitonsemicolon (array [1]) [0] .trim ()); break; case "content-disposition": if (Values.Length H> 0) _ContentDisPosition = VALUES [0] .trim (); /// reported by grandepuffo @ https://sourceforge.net/forum/Message.php?msg_id=2589759 // _ ContentFileName = VALUES [1] ; If (VALUES.LENGTH> 1) {_ContentFileName = VALUES [1];} else {_contentFileName = ""

IF (_ContentFileName == ") _ContentFileName = srReader.readline ();

_contentFileName = _contentFileName.Replace ( "/ t", ""); _contentFileName = Utility.GetQuotedValue (_contentFileName, "=", "filename"); _contentFileName = Utility.DecodeText (_contentFileName); break; case "CONTENT-ID": _ContentId = Utility.Splitonsemicolon (array [1]) [0] .trim ('<'). Trim ('>'); Break;}} ///

////////////////////// summary> /// encoding to verify /// true if encoding private bool IsEncoding (string encoding) {return _contentTransferEncoding.ToLower (). IndexOf ( Encoding.tolower ())! = -1;}

///

/// Decode the attachment to text /// /// Decoded attachment text public string decodeastext () {string decodedattachment = NULL;

try {if (_contentType.ToLower () == "message / rfc822" .ToLower ()) decodedAttachment = Utility.DecodeText (_rawAttachment); else if (_contentTransferEncoding = null!) {decodedAttachment = _rawAttachment;

IF ("iSencoding (" 7bit ") {IF (iSencoding (" 8bit ") && _ContentCharset! =") decodedattachment = utility.change (decodedattachment, _contentcharset);

if (Utility.IsQuotedPrintable (_contentTransferEncoding)) decodedAttachment = DecodeQP.ConvertHexContent (decodedAttachment); else if (IsEncoding ( "8bit")) decodedAttachment = decodedAttachment; else decodedAttachment = Utility.deCodeB64s (Utility.RemoveNonB64 (decodedAttachment));}} else if (! _contentCharset = null) decodedAttachment = Utility.Change (_rawAttachment, _contentCharset); //Encoding.Default.GetString(Encoding.GetEncoding(_contentCharset).GetBytes(_rawAttachment)); else decodedAttachment = _rawAttachment;} catch {decodedAttachment = _rawAttachment ;} return decodedAttachment;} ///

/// decode attachment to be a message object /// /// message public Message DecodeAsMessage () {bool blnRet = false Return New Message (Ref BLNRET, "", False, _Rawattachment, False;}

///

/// Decode the attachment to bytes /// /// decoded attachment bytes public bytes [] decodaSbytes () {i (_rawattachment == null) Return NULL; if (_ContentFileName! = ") {byte [] decodedbytes = null;

if (_contentType = null && _contentType.ToLower () == "message / rfc822" .ToLower ()!) decodedBytes = Encoding.Default.GetBytes (Utility.DecodeText (_rawAttachment)); else if (! _contentTransferEncoding = null) {string ByTContent = _rawattachment;

if {if (IsEncoding ( "8bit") && _contentCharset = null & _contentCharset = ""!!) bytContent = Utility.Change (bytContent, _contentCharset) (IsEncoding ( "7bit")!); if (Utility.IsQuotedPrintable (_contentTransferEncoding) ) decodedBytes = Encoding.Default.GetBytes (DecodeQP.ConvertHexContent (bytContent)); else if (IsEncoding ( "8bit")) decodedBytes = Encoding.Default.GetBytes (bytContent); else decodedBytes = Convert.FromBase64String (Utility.RemoveNonB64 (bytContent ));} else decodedBytes = Encoding.Default.GetBytes (bytContent);!} else if (_contentCharset = null) decodedBytes = Encoding.Default.GetBytes (Utility.Change (_rawAttachment, _contentCharset)); //Encoding.Default.GetString (Encoding.Getencoding (_ContentCharset) .GetBytes (_rawattachment)); else decodedBytes = Encoding.default.getBytes (_rawattachment);

Return decodedbytes;} else {return null;}}

Public int compareto (object attachment) {return (this.rawattachment.compareto ((attachment)). Rawattachment);}}

Public Enum MessageImportanceType {high = 5, NORMAL = 3, Low = 1}

///

/// decoding quoted-printable text ///// public class decodeqp {public decodeqp () {}

///

/// decoding quoted-printable string /// /// quoted-printable encode String /// encoding method /// decoded string public static string ConvertHexToString (string hexstring, string encoding) {try {return ConvertHexToString (hexstring, System.Text.Encoding.GetEncoding (encoding)) ;} Catch {return convertHexContent (HexString);}} /// /// decoding quoted-printable string /// /// quoted-printable encoded string < / param> /// encoding method /// decoded string public static string ConvertHexToString (string hexstring, encoding encode) {try {if (hexstring = = NULL || HexString.Equals (")) Return" "

IF (HexString.StartSwith ("=")) HexString = HexString.Substring (1);

String [] AHEX = HexString.Split (new char [1] {'='}); byte [] ABYTE = New Byte [AHEX.LENGTH];

For (int i = 0; i

///

/// decoding quoted-printable string at a position /// quoted-printable encoded string /// Encoding method, "default" is suggested /// position to start, normally 0 /// decoded string public static string ConvertHexContent (string hexstring, Encoding encode, long nStart) {if (nStart> = Hexstring.Length) return hexstring; // to hold string to be decoded StringBuilder sbHex = new StringBuilder (); sbHex.Append ( "") ; // to hold decoded string StringBuilder sbEncoded = new StringBuilder (); sbEncoded.Append ( ""); // wether we reach Quoted-Printable string bool isBegin = false; string temp; int i = (int) nStart;

While (i

While (i

} Else {if (isbegin) // we have got the how quoted-printable string, break it break; sbencoded.Append (Temp); // not quoted-printable string, Put IT INTO BUFFER i ;}

} // decode quoted-printable string sbencoded.append (textHextString (Sbhex.toString (), eNCode);}

Return sbencoded.toString ();

///

/// Decoding quotedable and beginning sale default encoding and begin at 0 /// /// quoted-printable encode String // / decoded string public static string converThexContent (String HexString) {if (HexString == Null || HexString.Equals (")) Return HEXSTRING;

Return ConvertHexContent (HexString, Encoding.default, 0);

}

///

/// Message Parser /// public class Message {#region Member Variablesprivate ArrayList _attachments = new ArrayList ();. Private string _rawHeader = null; private string _rawMessage = null; private string _rawMessageBody = null; private int _attachmentCount = 0; private string _replyTo = null; private string _replyToEmail = null; private string _from = null; private string _fromEmail = null; private string _date = null; private string _dateTimeInfo = null; private string _subject = null ; private string [] _to = new string [0]; private string [] _cc = new string [0]; private string [] _bcc = new string [0]; private ArrayList _keywords = new ArrayList (); private string _contentType = null; private string _contentCharset = null; private string _reportType = null; private string _contentTransferEncoding = null; private bool _html = false; private long _contentLength = 0; private string _contentEncoding = null; private string _returnPath = null; p rivate string _mimeVersion = null; private string _received = null; private string _importance = null; private string _messageID = null; private string _attachmentboundry = null; private string _attachmentboundry2 = null; private bool _hasAttachment = false; private string _dispositionNotificationTo = null; private ArrayList _MessageBody = new arraylist (); private string _basepath = null; private bool _autodecodemstnef = false; private haShtable _customHeaders = new hashtable ();

#ndregion

#Region Properties

///

/// Custom Headers /// Public HashTable CustomHeaders {Get {Return_CustomHeaders;} set {_customHeaders = Value;}} /// /// WHether Auto decoding MS- Tnef attachment files /// public bool autodocodemstnef {get {return _autodecodemstnef;} set {_autodecodemstnef = value;}}

///

/// path to extract ms-tnef attachment files /// public string basepath {get {return _basepath;} set {try {i (value.endswith ("//")))) _basepath = value; else _basepath = value "//";} catch {}}}

///

/// Message Keywords /// public arraylist keywords {get {return_keywords;}}

///

/// disposition notification /// public string dispositionnetificationto {get {return _dispositionNotificationto}}

///

/// received server /// public string received {get {return_received;}}

///

/// Importance level /// public string Importance {get {return_importance;}}

///

/// importance level type /// public MessageImportanceType ImportanceType {get {switch (_importance.ToUpper ()) {case "5": case "HIGH": return MessageImportanceType.HIGH; case "3": case "NORMAL": return MessageImportanceType.NORMAL; case "1": case "LOW": return MessageImportanceType.LOW; default: return MessageImportanceType.NORMAL;}}} /// /// Content Charset /// public string contentcharset {get {return_contentcharset;}}

///

/// Content Transfer Encoding /// public string contentTransferencoding {get {return _contentTransferenCoding;}}

///

/// Message Bodies /// public arraylist messagebody {get {return_MessageBody;}}

///

/// attachment boundry /// public string attachmentBoundry {get {return_attachmentBoundry;}}

///

/// alternate attachment boundry /// public string attachmentBoundry2 {get {return_attachmentBoundry2;}}

///

/// attachment count /// public int attachmentcount {get {return_attachment;}}

///

/// attachments /// public arraylist attachments {get {return_attachments;}}

///

/// cc /// public string [] cc {get {return_cc;}}

///

/// bcc /// public string [] bcc {get {return_bcc;}}

///

/// t /// public string [] to {get {return_to;}} /// ///content encoding /// public string Contentencoding {get {return_contentence;

///

/// content length ///

///

/// Content Type /// public string contenttype {get {return_contenttype;}}

///

/// Report Type /// public string reporttype {get {return_reporttype;}}

///

/// html /// public bool html {get {return_html;}}

///

/// Date /// public string date {get {return_date;}}

///

/// DateTime info /// public string datetimeInfo {get {return _datetimeInfo;}}

///

/// from name /// public string from {get {return_from;}}

///

/// from email /// public string ragingmail {get {return_fromemail;}}

///

/// reply to name /// public string replyto {get {return_replyto;}}

///

/// reply to email /// public string replytoemail {get {return_replytoemail;}}

///

/// WHETHER HAS ATTACHMENT / / / public bool Hasattachment {get {return_hasattachment;}}

///

/// Raw Message Body /// public string RawMessageBody {get {return _rawMessageBody;}} /// /// Message ID /// public String MessageId {raet _MessageId;}

///

/// mime version /// public string mimeversion {get {return_mimeversion;}}

///

/// raw header /// public string rawheader {get {return_rawheader;}}

///

/// Raw Message /// public string rawMessage {get {return_rawmessage;}}

///

/// Return path /// }}}

///

/// Subject /// public string subject {get {return_subject;}}

#ndregion

{_ _b (); _keywords = null; _keywords = null;........................... .. _MessageBody = null; _CustomHeaders.clear (); _CustomHeaders = null;

///

/// new message /// /// Reference for the finishing state /// Path to extract MS-TNEF attachment files /// whether auto decoding MS-TNEF attachments /// whether only decode the header without body /// file of email content to load from public Message (ref bool blnFinish, string strBasePath, bool blnAutoDecodeMSTNEF, bool blnOnlyHeader, string strEMLFile) {string strMessage = null; if (Utility.ReadPlainTextFromFile (strEMLFile, ref strMessage)) {NewMessage (ref blnFinish, strBasePath, blnAutoDecodeMSTNEF, strMessage, blnOnlyHeader);} else blnFinish = true;} /// /// New Message /// /// path to extract MS-TNEF Attachment Files //////// whether auto decoding MS-TNEF attachments /// raw message content /// whether only decode the header without body public Message (ref bool blnFinish, string strBasePath, bool blnAutoDecodeMSTNEF, string strMessage, bool blnOnlyHeader) {NewMessage (ref blnFinish, strBasePath, blnAutoDecodeMSTNEF, strMessage, blnOnlyHeader);}

///

/// new message /// Reference for the finishing state /// RAW message content /// whether only decode the header without body public Message (ref bool blnFinish, string strMessage, bool blnOnlyHeader) {NewMessage (ref blnFinish, "", False, StrMessage, BLNONLYHEADER;} /// /// new message /// /// Reference for the finishing state /// < Param name = "strmessage"> Raw Message Content Public Message (Ref Bool BLNFINISH, STRING STRING STRING STRING STRISSAGE (Ref BLNFINISH, ", FALSE, STRMESSAGE, FALSE);}

///

/// Get Valid attachment /// /// attachment index in the attachments collection //// attachment public Attachment getAttachment (int intAttachmentNumber) {if (intAttachmentNumber <0 || intAttachmentNumber> _attachmentCount || intAttachmentNumber> _attachments.Count) {Utility.LogError ( "getAttachment (): attachment not exist"); throw new ArgumentOutOfRangeException ( "intAttachmentNumber" }} Return (attachment) _attachments [intattachmentnumber];

///

/// new message /// /// Reference for the finishing state /// Path to extract MS-TNEF attachment files /// whether auto decoding MS-TNEF attachments /// raw message content /// whether only decode the header without body /// construction result whether successfully new a message private bool NewMessage (ref bool blnFinish, string strBasePath , bool blnAutoDecodeMSTNEF, string strMessage, bool blnOnlyHeader) {StringReader srdReader = new StringReader (strMessage); StringBuilder sbdBuilder = new StringBuilder (); _basePath = strBasePath; _autoDecodeMSTNEF = blnAutoDecodeMSTNEF; _rawMessage = strMessage;

string strLine = srdReader.ReadLine (); while (Utility.IsNotNullTextEx (strLine)) {sbdBuilder.Append (strLine "/ r / n"); ParseHeader (sbdBuilder, srdReader, ref strLine); if (Utility.IsOrNullTextEx (strLine )) Break; Else strline = Srdreader.readline ();

_Rawheader = sbdbuilder.tostring ();

SetAttachmentBoundry2 (_RAWHEADER);

IF (_ContentLength == 0) _ContentLength = StrMessage.Length; //_rawmessagebody.length

IF (blnonlyheader == false) {_RAWMESSAGEBODY = SRDReader.ReadToEnd (). Trim ();

// the auto reply mail by outlook uses ms-tnef format if ((_hasAttachment == true && _attachmentboundry = null) || MIMETypes.IsMSTNEF (_contentType)!) {Set_attachments (); if (this.Attachments.Count> 0) {Attachment at = this.getattachment (0); if (at! = Null && at.nottachment) this.getMessageBody (at.decodeastext ()); else {} // in case body parts as text [0] HTML [1 ] IF (this.attachments.count> 1 &&! This.isreport ()) {at = this.getatchment (1); if (at! = Null && at.nottachment) this.getMessageBody (at.decodeastext ()); Else {}}} else {}} else {getMessageBody (_RAWMESSAGEBODY);}}

BLNFINISH = True; Return True;

///

/// Parse Message Body /// /// RAW Message Body /// Message Body public String getTextBody (string strbuffer) {if (strbuffer.endswith)) Return strbuffer.substring (0, strbuffer.length - "/R/N.".Length); else returnffer;}

///

/// Parse Message Body /// /// RAW Message Body public void getMessageBody (string strboffer) {int end, begin String body; string encoding = "";

Begin = End = 0; _MessageBody.clear ();

try {if (Utility.IsOrNullTextEx (strBuffer)) return; else if (Utility.IsOrNullTextEx (_contentType) && _contentTransferEncoding == null) {_messageBody.Add (GetTextBody (strBuffer));} else if (_contentType = null && _contentType!. IndexOf ( "digest")> = 0) {// this is a digest method // ParseDigestMessage (strBuffer); _messageBody.Add (getTextBody (strBuffer));} else if (_attachmentboundry2 == null) {body = getTextBody (strBuffer ); if (Utility.IsQuotedPrintable (_contentTransferEncoding)) {body = DecodeQP.ConvertHexContent (body);} else if (Utility.IsBase64 (_contentTransferEncoding)) {body = Utility.deCodeB64s (Utility.RemoveNonB64 (body));} else if (Utility.IsNotNullText (_contentCharset)) {body = Encoding.GetEncoding (_contentCharset) .GetString (Encoding.Default.GetBytes (body));} _messageBody.Add (Utility.RemoveNonB64 (body));} else {begin = 0;

While (begin! = -1) {// Find "/ r / n / r / n" Denoting end of header begin = strbuffer.indexof ("-" _ _TtachmentBoundry2, begin); if (begin! = -1) {Encoding = mimeTypes.getContentTransferencoding (Strbuffer, Begin);

Begin = strbuffer.indexof ("/ r / n / r / n", begin 1); //strbuffer.lastindexofany (alphabet.tochararray ());

// Find End of text end = strbuffer.indexof ("-" _ _ttachmentboundry2, begin 1);

IF (begin! = -1) {IF (end! = -1) {begin = 4; if (begin> = End) Continue; Else IF (this._contentencoding! = null && this._contentencoding.indexof ("8bit) ")! = -1) body = utility.change (strbuffer.substring (begin, end - begin - 2), _contentcharset; else body = strbuffer.substring (begin, end - begin - 2);} else {body = strBuffer.Substring (begin);} if (Utility.IsQuotedPrintable (encoding)) {string ret = body; ret = DecodeQP.ConvertHexContent (ret); _messageBody.Add (ret);} else if (Utility.IsBase64 (encoding)) {String Ret = UTILITY.Removenonb64 (Body); RET = Utility.Decodeb64S (RET); if (Ret! = "/ 0") _MessageBody.Add (Ret); else _MessageBody.Add (body);} else _MessageBody.add Body);

IF (End == -1) Break;} else {ik;}} else {if (_MESSAGEBODY.COUNT == 0) {_MessageBody.add (strbuffer);} Break;}}}} catch (Exception E) {Utility .LoGerror ("GetMessageBody ():" E.MESSAGE); _MESSAGEBODY.ADD (Utility.DecodeB64S (Strbuffer);}

IF (_MESSAGEBODY.COUNT> 1) _html = true;

///

/// verify if the message is a report /// /// if it is a report message, return true, else, false public bool isreport ) {IF (Utility.isnotn ELLTEXT (_ContentType)) Return (_ContentType.tolower (). Indexof ("Report" .tolower ())! = -1); Else Return false;} /// /// verify IF the attachment is mime email file /// /// attachment /// if mime email file, return true, else, false public bool IsMIMEMailFile (Attachment attItem) {try {return (attItem.ContentFileName.ToLower (). EndsWith ( ". eml" .ToLower ()) || attItem.ContentType.ToLower () == "message / rfc822" .ToLower ());} Catch (exception e) {utility.loGerror ("ismimemailfile ():" E.MESSAGE); RETURN FALSE;}}

///

/// translate pictures url within the body /// /// Message body /// pictures collection /// translated message body public string TranslateHTMLPictureFiles (string strBody, Hashtable hsbFiles) {try {for (int i = 0; i

strBody = strBody.Replace (att.ContentFileName, hsbFiles [att.ContentFileName] .ToString ());}}} catch (Exception e) {Utility.LogError ( "TranslateHTMLPictureFiles ():" e.Message);} return strBody } ///

/// Translate Pictures Url with the body /// /// Message body /// path of the pictures /// translated message body public string TranslateHTMLPictureFiles (string strBody, string strPath) {try {if (! strPath.EndsWith (" // ")) { StrPath = "//";} for (int i = 0; i

///

/// Get The Proper attachment file name /// /// attachment /// ProPERY ATTACHMENT FILE NAME Public String GetAtTachmentFileName (Attachment AttItem) {Int items = 0;

// return unique body file names for (int i = 0; i <_attachments.Count; i ) {if (attItem.ContentFileName == attItem.DefaultFileName) {items ; attItem.ContentFileName = attItem.DefaultFileName2.Replace ( "*" Items.tostring ());}} String name = attitectectFileName; return (name == null || name == ""? (isReport () == True? (this.ismimemailfile (attitect) == True? Attitem.defaultmimeFileName: attitem.defaultreportFileName): (attitem.content): (}): Name);

///

/// Save attachments to a defined path /// /// path to have attachments to be saved to //// True if Save Success, False If Failed Public Bool SavetTachments (String StrPath) {IF (Utility.isnotnullText (StrPath) {Try {BOOL BLNRET = TRUE

IF ("//")) {strpath = "//";} for (int i = 0; i

///

/// Save attachment to file /// /// attachment ///

///

/// ///////////////////////////////////////////////////////////////// ///

SetAttachmentBoundry2 (_RAWMESSAGEBODY);

while (! processed) {if (Utility.IsNotNullText (_attachmentboundry)) {indexOf_attachmentstart = _rawMessageBody.IndexOf (_attachmentboundry, indexOf_attachmentstart) _attachmentboundry.Length; if (_rawMessageBody == "" || indexOf_attachmentstart <0) return;

Indexofattachmentend = _rawMessageBody.indexof (_ttachmentBoundry, IndexOf_attachmentStart 1);} else {indexofattachmentendnd = -1;}

// if (indexOfAttachmentEnd <0) return; if (! IndexOfAttachmentEnd = -1) {} else if (indexOfAttachmentEnd == -1 && processed && _attachmentCount == 0!) {Processed = true; indexOfAttachmentEnd = _rawMessageBody.Length;} else Return;

IF (indexof_attachmentstart == indexofattachmentend - 9) {indexof_attachmentStart = 0; Processed = true;

string strLine = _rawMessageBody.Substring (indexOf_attachmentstart, (indexOfAttachmentEnd - indexOf_attachmentstart - 2)); bool isMSTNEF; isMSTNEF = MIMETypes.IsMSTNEF (_contentType); att = new Attachment (strLine.Trim (), _contentType, isMSTNEF!);

(! MIMETypes.IsMSTNEF (att.ContentType) && AutoDecodeMSTNEF && isMSTNEF) // ms-tnef format might contain multiple attachments if {Utility.LogError ( "set_attachments (): found ms-tnef file"); TNEFParser tnef = new TNEFParser ( ); TNEFAttachment tatt = new TNEFAttachment (); Attachment attNew = null; tnef.Verbose = false; tnef.BasePath = this.BasePath; //tnef.LogFilePath=this.BasePath "OpenPOP.TNEF.log"; if (tnef .Opentnefstream (att.decodedasbytes ())) {if (tnef.parse ()) {for (iDictionaryEnumerator i = Tnef.attachments (). Getenumerator (); i.MOVENEXT (); {Tatt = (tnefattachment) i. Value; attNew = new Attachment (tatt.FileContent, tatt.FileLength, tatt.FileName, MIMETypes.GetMimeType (tatt.FileName)); _attachmentCount ; _attachments.Add (attNew);}} else Utility.LogError ( "set_attachments (): MS-TNEF File Parse Failed ");} else utility.loGerror (" set_attachments (): MS-TNEF File OP Else {_ttachmentcount ; _ttachments.add (att);

IndexOf_attachmentStart ;}}

///

/// Set alternative attachment boundry /// /// raw message private void SetAttachmentBoundry2 (string strBuffer) {int indexOfAttachmentBoundry2Begin = 0; int indexOfAttachmentBoundry2End = 0;. indexOfAttachmentBoundry2Begin = strBuffer.ToLower () IndexOf ( "Multipart / Alternative" .ToLower ()); if (! indexOfAttachmentBoundry2Begin = -1) {/ * indexOfAttachmentBoundry2Begin = strBuffer.IndexOf ( "boundary = /" ") ; indexOfAttachmentBoundry2End = strBuffer.IndexOf ( "/" ", indexOfAttachmentBoundry2Begin 10); if (!! indexOfAttachmentBoundry2Begin = - 1 && indexOfAttachmentBoundry2End = - 1) _attachmentboundry2 = strBuffer.Substring (indexOfAttachmentBoundry2Begin 10, indexOfAttachmentBoundry2End-indexOfAttachmentBoundry2Begin-10) .Trim (); * / Indexofattachmentboundry2begin = strbuffer.indexof ("boundary ="); if (indexofattachmentboundry2begin! = -1) {int P = strbuffer.indexof ("/ r / n", IndexofattachmentBoundry2Begin ); String s = strBuffer.Substring (indexOfAttachmentBoundry2Begin 29, 4); indexOfAttachmentBoundry2End = strBuffer.IndexOf ( "/ r / n", indexOfAttachmentBoundry2Begin 9); if (indexOfAttachmentBoundry2End == -1) indexOfAttachmentBoundry2End = strBuffer.Length; _attachmentboundry2 = Utility.RemoveQuote (strBuffer.Substring (indexOfAttachmentBoundry2Begin 9, indexOfAttachmentBoundry2End - indexOfAttachmentBoundry2Begin - 9));}} else {_attachmentboundry2 = _attachmentboundry;}}

///

/// Save Message Content to EML file /// /// String builder to hold header content /// string reader to get each line of the header /// first line content /// reference header line /// collection to hold every content line private void ParseStreamLines (StringBuilder sbdBuilder StringReader Srdreader, String Strigue, Ref string strline, arraylist alCollection {string strformmated; int in S = 0; alCollection.add (strValue);

SBDBUILDER.APPEND (STRLINE);

Strline = srdreader.readline ();

While (strline.trim ()! = "" && ("/ t") || Strline.StartSwith ("))) {strformmated = strline.substring (1); alCollection.add (utility.decodeline) (StrformMated); sbdbuilder.append (strline); strline = srdreader.readline (); intlines ;}

if (strLine = ""!) {sbdBuilder.Append (strLine);} else if (intLines == 0) {strLine = srdReader.ReadLine (); sbdBuilder.Append (strLine);} ParseHeader (sbdBuilder, srdReader, ref strLine }

///

/// PARSE MULTI-line header /// /// String reader to get each line of the header /// Collection key /// first line content /// reference header line /// collection to hold every content line private void ParseStreamLines (StringBuilder sbdBuilder, StringReader srdReader, String Strname, String Strign, REF STRING STRLINE, HASHTABLE HSTCOLLECTION {string strformmated; string strreturn = strval; int = 0;

//sbdbuilder.append(strline);

Strline = srdreader.readline (); while (strline.trim ()! = "" && (Strline.StartSwith ("/ t") || Strline.StartSwith ("))) {StrformMated = Strline.substring (1) ; strReturn = Utility.DecodeLine (strFormmated); sbdBuilder.Append (strLine "/ r / n"); strLine = srdReader.ReadLine (); intLines ; (! hstCollection.ContainsKey (strName))} if hstCollection.Add ( Strname, strreturn; if (strline! = ") {sbdbuilder.append (strline " / r / n ");} else if (intline == 0) {// strline = SrdReader.readLine (); // SBDBuilder.Append (strline "/ r / n");}

PARSEHEADER (SBDBuilder, SrdReader, ref strline);

///

/// PARSE MULTI-line header /// /// String Reader To Get Each Line of the Header /// first line content /// Reference header line /// return value /// decode each line private void ParseStreamLines (StringBuilder sbdBuilder, StringReader srdReader, string strValue, Ref string strline, reb string strreturn, {string strformmated; int = 0; strreturn = strements;

SBDBuilder.Append (Strline "/ R / N");

IF (blnlinedecode == true) strreturn = utility.decodeline (STRRETURN);

Strline = srdreader.readline (); while (strline.trim ()! = "" && (Strline.StartSwith ("/ t") || Strline.StartSwith ("))) {StrformMated = Strline.substring (1) ; strReturn = (blnLineDecode == true Utility.DecodeLine (strFormmated):? "/ r / n" strFormmated); sbdBuilder.Append (strLine "/ r / n"); strLine = srdReader.ReadLine (); intLines }

IF (Strline! = ") {sbdbuilder.append (strline " / r / n ");} else if (intline == 0) {strline = SrdReader.readLine (); sbdbuilder.append (strline " / r / N ");

If (! blnlineDecode) {strreturn = utility.removewhiteblanks (utility.decodetext (strreturn));}

PARSEHEADER (SBDBuilder, SrdReader, ref strline);

///

/// Parse the Headers Populating Respective Member Fields /// /// String Builder to hold the header content /// string reader to get each line of the header /// reference header line private void ParseHeader (StringBuilder sbdBuilder, StringReader srdReader, ref string strLine ) {String [] array = uTility.getHeadersValue (Strline); //regex.split(Strline, ":");

Switch (Array [0] .toupper ()) {CASE "to": _to = array [1] .split (','); for (int i = 0; i <_to.length; i ) {_to [i ] = UTility.Decodeline (_to [i] .trim ());} Break; Case "CC": _CC = array [1] .split (','); for (int i = 0; i <_cc.length ; i ) {_CC [i] = utility.decodeline (_CC [i] .trim ());

Case "BCC": _BCC = array [1] .split (','); for (int i = 0; i <_bcc.length; i ) {_bcc [i] = utility.decodeline (_bcc [i] .trim ());

Case "from": utility.parseemailaddress (array [1], ref _from, ref _froMEmail); Break;

Case "reply-to": utility.parseemailaddress (array [1], ref _replyto, ref _replytoemail); Break;

Case "Keywords": // MS Outlook Keywords Parsestreamlines (SBDBuilder, Srdreader, Array [1] .trim (), ref strline, _keywords;

Case "Received": ParsestreamLines (SBDBuilder, Srdreader, Array [1] .trim (), Ref strline, ref _received, true); Break;

Case "importance": _IMPORTANCE = Array [1] .trim ();

Case "disposition-notification-to": _dispositionNotificationTo = array [1] .trim (); break;

Case "mime-version": _mimeversion = array [1] .trim ();

Case "Subject": Case "thread-topic": string strret = null; for (int i = 1; i

Case "return-path": _RETURNPATH = array [1] .trim (). Trim ('>'). Trim ('<'); Break; Case "Message-ID": _MessageId = array [1] .trim ) .Trim ('>'). TRIM ('<'); Break;

Case "date": for (int i = 1; i

Case "content-length": _ContentLength = Convert.Toint32 (Array [1]); Break;

Case "content-transfer-encoding": _ContentTransferencoding = array [1] .trim (); break;

Case "Content-Type": // if already content type has been assigned if (_contenttype! = null) return;

Strline = array [1];

_CONTENTTYPE = Strline.Split (';') [0]; _ContentType = _ContentType.trim ();

INT INTCHARSET = Strline.indexof ("Charset ="); IF (IntCharset! = -1) {INT INTBOUND2 = strline.tolower (). Indexof (";", intcharset 8); if (intbound2 == -1) intBound2 = strLine.Length;. intBound2 - = (intCharset 8); _contentCharset = strLine.Substring (intCharset 8, intBound2); _contentCharset = Utility.RemoveQuote (_contentCharset);} else {intCharset = strLine.ToLower () IndexOf ( "Report-Type =". TOLOWER ()); if (INTCHARSET! = -1) {INT INTPOS = Strline.indexof (";", INTCHARSET 13); _ReportType = strline.substring (intcharset 12, intpos - intcharset - 13);} else if (strline.tolower (). Indexof ("boundary =". TOLOWER ()) == -1) {strline = srdreader.readline (); if (strline == ") Return; intcharset = strline.tolower (). Indexof ("charset =". TOLOWER ()); if (intcharset! = -1) _ContentCharset = strline.substring (intcharset 9, strline.Length - Intcharset - 10); ELS E IF (":")! = -1) {sbdbuilder.append (strline "/ r / n"); Parseheader (SBDBuilder, Srdreader, Ref strline); return;} else {sbdbuilder.Append Strline "/ r / n");}}} if (_ContentType == "text / plain") Return; Else IF (_ContentType.tolower () == "text / html" || _conteType.tolower (). Indexof ("Multipart /")! = -1) _html = true;

IF (strline.trim (). Length == _ContentType.Length 1 || strline.tolower (). Indexof ("Boundary =". TOLOWER ()) == -1) {strline = Srdreader.Readline (); if (strline == NULL || Strline == "|| strline.indexof (": ")! = -1) {sbdbuilder.append (strline " / r / n "); Parseheader (SBDBuilder, Srdreader, Ref strline );} Else {sbdbuilder.append (strline "/ r / n");} if (strline.tolower (). Indexof ("boundary =". TOLOWER ()) == -1) {_attachmentBoundry = Srdreader .Readline (); sbdbuilder.append (_attachmentboundry "/ r / n");} _ttachmentBoundry = strline;} else {/*if(-strline.indexof(";") !=-1) _attachmentBoundry = strline.split ( ';') [1]; else * / _attachmentBoundry = strline;}

INT INTBOUND = _TtachmentBoundry.tolower (). Indexof ("boundary ="); if (intBound! = -1) {int INTBOUND2 = _attachmentBoundry.tolower (). Indexof (";;", intbound 10); if (INTBound2 = = -1) intBound2 = _attachmentboundry.Length; intBound2 - = (intBound 9); _attachmentboundry = _attachmentboundry.Substring (intBound 9, intBound2);} _attachmentboundry = Utility.RemoveQuote (_attachmentboundry); _hasAttachment = true;

Break;

Default: if (Array.Length> 1) // Here We Parse All Custom Headers {String Headername = Array [0] .trim (); if (Headername.toupper (). StartSwith ("x")) // Every Custom Header Starts with "x" {Parsestreamlines (SBDBuilder, Srdreader, Headername, Array [1] .trim (), ref strline, _customheaders;}} Break;}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} public class MIMETypes {public const string MIMEType_MSTNEF = "application / ms-tnef"; private const string Content_Transfer_Encoding_Tag = "Content-Transfer-Encoding"; private static Hashtable _MIMETypeList = null;

public static string GetContentTransferEncoding (string strBuffer, int pos) {int begin = 0, end = 0; begin = strBuffer.ToLower () IndexOf (Content_Transfer_Encoding_Tag.ToLower (), pos);. if (begin = -1!) {end = strBuffer.ToLower () IndexOf ( "/ r / n" .ToLower (), begin 1);. return strBuffer.Substring (begin Content_Transfer_Encoding_Tag.Length 1, end - begin - Content_Transfer_Encoding_Tag.Length) .Trim () } Else return "";

public static bool IsMSTNEF (string strContentType) {if (strContentType = null & strContentType = ""!!) if (strContentType.ToLower () == MIMEType_MSTNEF.ToLower ()) return true; else return false; else return false;}

Public static string contentType (String strextension) {if (_MimetyPelist.Containskey (strextension) Return_MimetyPelist [strextension] .tostring (); else return null;}

Public Static Hashtable MimeTypelist {Get {Return_MimetyPelist;} set {_mimetyPelist = value;}}

~ MimeTypes () {_mimetypelist.clear (); _MimeTypelist = NULL;}

Public mimeTypes () {_mimetyPelist.add (". 323", "text / h323); _MimeTypelist.add (". 3gp "," video "); _MimeTypelist.add (". 3GPP "," Video / 3GPP "); _MimeTypelist.add (". Acp "," audio / x-mei-aac "); _MimeTypelist.add (". ACT "," text / xml "); _MimeTypelist.add (". Actproj "," Text / plain "); _MimeTypelist.add (". ADE "," Application / MsAccess "); _MimeTypelist.add (". ADP "," Application / Msaccess "); _MimeTypelist.add (". ai "," Application / PostScript "); _MimeTypelist.add (". AIF "," Audio / AIFF "); _MimetyPelist.Add (". AIFC "," Audio / AIFF "); _MimeTypelist.add (". AIFF "," Audio / AIFF ") _MimeTypelist.add (". Asf", "video / x-ms-asf"); _MimeTypelist.add (". Asm", "text / plain"); _MimeTypelist.add (". Asx", "video / x -MS-ASF "); _MimeTypelist.add (". au "," audio / Basic "); _MimeTypelist.add (". Avi "," Video / Avi "); _MimeTypelist.add (". BMP "," Image / BMP "); _MimeTypelist.add (". BWP "," Application / X-bwpreview); _MimeTypelist.add (". c", "text / plain"); _MimeTypelist.add (". cat", "Application /VND.MS-PKI.SECCAT "); _MimeTypelist.add (". Cc", "text / plain"); _MimeTypelist.add (". Cdf", "application / x-cdf"); _MimeTypelist.add (". Cer", "Application / X-X509- CA-CERT "); _MimeTypelist.add (". COD "," text / plain "); _MimeTypelist.add (". CPP "," text / plain "); _MimeTypelist.add (". crl "," Application / PKIX-CRL "); _MimeTypelist.add ("

.CRT "," Application / X-X509-CA-CA-CERT "); _MimeTypelist.add (". cs "," text / plain "); _MimeTypelist.add (". css "," text / css "); _MimetyPelist .Add (". Csv", "application / vnd.ms-excel"); _MimeTypelist.add (". Cxx", "text / plain); _MimeTypelist.add (" dbs "," text / plain ") _MimeTypelist.add (". Def", "text / plain"); _MimeTypelist.add (".der", "Application / X-X509-ca-cert"); _MimeTypelist.add (". Dib", "Image" / BMP "); _MimeTypelist.add (". DIF "," VIDEO / X-DV "); _MimeTypelist.add (". DLL "," Application / X-msdownload "); _MimeTypelist.add (". doc ", "Application / Msword"); _MimeTypelist.add (". dot", "Application / Msword"); _MimeTypelist.add (". dsp", "text / plain"); _MimeTypelist.add (". dsw", "Text / plain "); _MimeTypelist.add (". DV "," VIDEO / X-DV "); _MimeTypelist.add (". EDN "," Application / VND.ADOBE.EDN "); _MimeTypelist.add (". EML "" Message / RFC822 "); _MimeTypelist.add (". EPS "," Application / PostScript "); _MimeTypelist.add (". ETD "," Application / X-EBX "); _MimeTypelist.add (". ETP "," text / plain "); _MimeTy Pelist.add (". EXE", "Application / X-msdownload"); _MimeTypelist.add (". ext", "text / plain"); _MimeTypelist.add (". fdf", "application / vnd.fdf" ); _MimeTypelist.add (". Fif", "application / fractals); _MimeTypelist.add (". Fky "," text / plain "); _MimeTypelist.add (". Gif "," image / gif "); _MimeTypelist.add (". Gz", "

Application / x-gzip "); _MimeTypelist.add (". h "," text / plain "); _MimeTypelist.add (". HPP "," text / plain "); _MimeTypelist.add (". hqx "," Application / mac-binhex40 "); _MimeTypelist.add (". hta "," application / hta "); _MimeTypelist.add (". htc "," text / x-component); _MimeTypelist.add (". htm" "Text / html"); _MimeTypelist.add ("html", "text / html"); _MimeTypelist.add (". htt", "text / webviewhtml); _mimetypelist.add (". hxx "," Text / plain "); _MimeTypelist.add (". I "," text / plain "); _MimeTypelist.add (". Iad "," Application / X-IAD "); _MimeTypelist.add (". ICO "," Image / x-icon "); _MimeTypelist.add (". ICS "," text / calendar "); _MimeTypelist.add (". id1 "," text / plain "); _MimeTypelist.add (". III "," Application / x-iPhone "); _MimeTypelist.add (". Inc "," text / plain "); _MimeTypelist.add (" infoPathXML "," Application / MS-InfoPath.xml "); _MimeTypelist.add (". INL "," text / plain "); _MimeTypelist.add (". INS "," Application / X-Internet-Signup "); _MimeTypelist.add (" IQY "," Text / X-MS-IQY "); _MimeTypelist.add (". I SP "," Application / X-Internet-Signup "); _MimeTypelist.add (" java "," text / java); _MimeTypelist.add (". jfif", "image / jpeg"); _MimeTypelist.add ( ".jnlp", "Application / X-java-jnlp-file"); _MimeTypelist.add ("jpe", "image / jpeg"); _MimetyPelist.add ("jpeg", "image / jpeg"); _MimeTypelist.add (". Jpg", "image / jpeg"

); _MimeTypelist.add ("jsl", "text / plain); _MimeTypelist.add (" kci "," text / plain "); _MimeTypelist.add (". La1 "," audio / x-lique- "); _MimeTypelist.add (". lar "," application / x-laplayer-reg "); _MimeTypelist.add (". latex "," application / x-latex "); _MimeTypelist.add (". LAVS " "AUDIO / X-Liquid-Secure"); _MimeTypelist.add (". LGN", "text / plain"); _MimeTypelist.add (". lmsff", "Audio / X-la-LMS"); _MimeTypelist. Add (". LQT", "Audio / X-LA-LQT"); _MimeTypelist.add (". LST", "text / plain"); _MimeTypelist.add (". M1V", "Video / MPEG"); _MimetyPelist.add (". M3U", "Audio / MPEGURL"); _MimeTypelist.add (". M4E", "Video / MPEG4"); _MimeTypelist.add (". Mac", "image / x-macpaint"); _MimetyPelist.add (". Mak", "text / plain"); _MimeTypelist.add (".man", "application / x-troff-man"); _MimeTypelist.add (". Map", "text / plain" _MimeTypelist.add (". MDA", "Application / MsAccess"); _MimeTypelist.add (". MDB", "Application / MsAccess"); _MimetyPelist.Add (". MDE", "Application / MsAccess"); _MimeTypelist.add (". MDi" "Image / vnd.ms-modi"); _MimeTypelist.add (". mfp", "application / x-shockwave-flash"); _MimeTypelist.add (". MHT", "Message / RFC822"); _MimeTypelist. Add (". MHTML", "Message / RFC822"); _MimeTypelist.add (". MID", "Audio / MID"); _MimeTypelist.add (". MIDI", "Audio / MID"); _MimeTypelist.add ( ".mk", "text / plain");

_MimeTypelist.add (". MND", "Audio / X-Musicnet-Download"); _MimeTypelist.add (". Mns", "audio / x-musicnet-stream); _MimeTypelist.add (". Mp1 "," AUDIO / MP1 "); _MimeTypelist.add (". MP2 "," Video / MPEG "); _MimeTypelist.add (". MP2V "," Video / MPEG "); _MimeTypelist.add (". mp3 "," Audio / "_MimeTypelist.add (". mp4 "," video / mp4 "); _MimeTypelist.add (". mpa "," video / mpeg "); _MimeTypelist.add (". MPE "," Video / MPEG " _MimeTypelist.add (". MPEG", "Video / MPEG"); _MimeTypelist.add (". MPF", "Application / VND.ms-MediaPackage"); _MimeTypelist.add (". MPG", "VIDEO / "); _MimeTypelist.add (". MPG4 "," VIDEO / MP4 "); _MimeTypelist.add (". MPGA "," Audio / RN-MPEG "); _MimeTypelist.add (". mpv2 "," video / "); _MimeTypelist.add (" nmw "," application / nmwb); _MimeTypelist.add (". nws", "message / RFC822)); _MimeTypelist.add (". ODC "," Text / x- MS-ODC "); _MimeTypelist.add (". ODH "," text / plain "); _MimeTypelist.add (". ODL "," text / plain "); _MimeTypelist.add (". p10 "," Application / PKCS10 "); _MimeTypelist.add (". p1 2 "," Application / X-PKCS12 "); _MimeTypelist.add (". P7b "," Application / X-PKCS7-Certificate "); _MimeTypelist.add (". P7c "," Application / PKCS7-MIME "); _MimeTypelist.add (". P7m", "Application / PKCS7-MIME"); _MimeTypelist.add (". P7r", "Application / X-PKCS7-CertreqResp"); _MimeTypelist.add (". P7s", "

Application / PKCS7-Signature "); _MimeTypelist.add (". PCT "," Image / Pict "); _MimeTypelist.add (". PDF "," Application / PDF "); _MimeTypelist.add (". pdx "," Application / vnd.adobe.pdx "); _MimeTypelist.add (". pfx "," application / x-pkcs12); _MimeTypelist.add ("pic", "image / Pict"); _MimetyPelist.add (". Pict "," Image / Pict "); _MimeTypelist.add (" pko "," Application / VND.ms-Pki.pko "); _MimeTypelist.add (" png "," image / png "); _MimetyPelist. Add ("pnt", "image / x-macpaint"); _MimeTypelist.add ("pntg", "image / x-macpaint"); _MimeTypelist.add (". Pot", "Application / VND.MS- PowerPoint "); _MimeTypelist.add (" ppa "," application / vnd.ms-powerPoint "); _MimetyPelist.add (". pps "," application / vnd.ms-powerPoint "); _MimetyPelist.add (". PPT "," Application / VND.ms-PowerPoint "); _MimeTypelist.add (" .prc "," text / plain "); _MimeTypelist.add (" .prf "," Application / Pics-Rules "); _MimetyPelist. Add (". Ps", "application / postscript"); _MimeTypelist.add ("pub", "application / vnd.ms-publisher"); _MimeTypelist.add (".pwz", "Application / VND.ms-PowerPoint"); _MimeTypelist.add (". Qt", "Video / QuickTime"); _MimeTypelist.add (". QTI", "Image / X-QuickTime") _MimeTypelist.add (". Qtif", "image / x-quicktime); _MimetyPelist.add (". Qtl "," application / x-quicktimeplayer "); _MimeTypelist.add (". QUP "," Application / X -quicktimeUpdater "); _MimeTypelist.add (". r1m ","

Application / vnd.rn-recording "); _MimeTypelist.add (". r3t "," text / vnd.rn-realText3d "); _MimeTypelist.add (". ra "," audio / vnd.rn-realaudio); _MimeTypelist.add (". Ram", "audio / x-pn-realaudio); _MimeTypelist.add (" rat "," application / rat-file "); _MimeTypelist.add (". Rc "," text) "); _MimeTypelist.add (". rc2 "," text / plain); _MimeTypelist.add (". rct", "text / plain"); _MimeTypelist.add (". REC", "Application / VND. Rn-recording "); _MimeTypelist.add (". rgs "," text / plain); _MimeTypelist.add (". rjs", "application / vnd.rn-realsystem-rjs"); _MimeTypelist.add (". RJT "," Application / Vnd.rn-realsystem-rjt "); _MimetyPelist.add (". rm "," application / vnd.rn-realmedia); _MimeTypelist.add (". RMF", "Application / VND. Adobe.rmf "); _MimeTypelist.add (". RMI "," Audio / MID "); _MimeTypelist.add (". rmj "," application / vnd.rn-realsystem-rmj "); _MimeTypelist.add (". RMM "," AUDIO / X-PN-ReaRaudio "); _MimeTypelist.add (" rms "," application / vnd.rn-realmedia-secure "); _MimeTypelist.add (". Rmvb "," Application / VND.RN-Realmedia-VBR "); _MimeTypelist.add (". RMX "," Application / Vnd.rn-realsystem-rmx "); _MimeTypelist.add (". RNX "," Application / VND.RN-RealPlayer " _Mimetypelist.add (". Rp", "image / vnd.rn-realpix"); _MimeTypelist.add (". Rpm", "audio / x-pn-realaudio-plugin"); _MimeTypelist.add (". RQY "," text / x-ms-rqy "); _MimeTypelist.add (". rsml ","

Application / vnd.RN-RSML "); _MimeTypelist.add (". rt "," text / vnd.rn-realText "); _MimeTypelist.add (". RTF "," Application / Msword "); _MimeTypelist.add ( ".rul", "text / plain"); _MimeTypelist.add (". rv", "video / vnd.rn-realvideo"); _MimeTypelist.add (". s", "text / plain"); _mimetyPelist. Add (". SC2", "Application / SCHDPL32"); _MimeTypelist.add (". SCD", "Application / Schdpl32)); _MimeTypelist.add (". SCH "," Application / Schdpl32 "); _MimeTypelist.add ( ".sct", "text / scriptle"); _MimeTypelist.add (". SD2", "Audio / X-SD2"); _MimeTypelist.add (". SDP", "Application / SDP"); _MimeTypelist.add ( ".sit", "Application / X-stuffit"; _MimeTypelist.add (". SLK", "Application / VND.MS-Excel"); _MimeTypelist.add (". SLN", "Application / Oct-stream" _MimeTypelist.add (". SMI", "Application / SMIL"); _MimeTypelist.add (". SMIL", "Application / SMIL"); _MimeTypelist.add (". SND", "Audio / Basic"); _MimeTypelist.add (". Snp", "application / msaccess"); _MimeTypelist.add (". SPC", "Application / X-PKCS7-CERTIFICATES"); _MI Metypelist.add (". SPL", "Application / Futuresplash); _MimetyPelist.add (". SQL "," text / plain "); _MimeTypelist.add (". SRF "," text / plain); _mimetyPelist. Add (". SSM", "Application / streamingMedia"); _MimeTypelist.add (". SST", "Application / VND.ms-Pki.certStore"); _MimetyPelist.add (". STL", "Application / VND. MS-PKI.STL "); _MimeTypelist.add ("

.swf "," Application / X-ShockWave-Flash "); _MimeTypelist.add (". Tab "," text / plain "); _MimeTypelist.add (". TAR "," Application / X-TAR "); _MimeTypelist .Add (". TDL", "text / xml"); _MimeTypelist.add (". TGZ", "Application / X-compressed"); _MimeTypelist.add (". TIF", "Image / Tiff"); _mimetyPelist .Add (". TIFF", "image / TIFF"); _MimeTypelist.add (". TLH", "text / plain"); _MimeTypelist.add (". Tli", "text / plain"); _mimetypelist.add (".torrent", "Application / X-bittorrent"); _MimeTypelist.add (". TRG", "text / plain"); _MimeTypelist.add (". txt", "text / plain"); _MimeTypelist.add (".udf", "text / plain"); _MimeTypelist.add (". UDT", "text / plain"); _MimeTypelist.add (". ULS", "text / IULS"); _MimeTypelist.add (" "text / plain"); _MimeTypelist.add (". usr", "text / plain); _MimeTypelist.add (". VB "," text / plain "); _mimetypelist.add (". vcf "," text / x-vcard "); _MimeTypelist.add (". vcproj "," text / place "); _MimeTypelist.add (". viw "," text / plain "); _MimeTypelist.add (". vpg "," Application / X-VPEG005 "); MimeTypelist.add (". Vspscc", "text / plain"); _MimeTypelist.add (". Vsscc", "text / plain); _MimeTypelist.add (". Vsscc "," text / plain "); _MimetyPelist. Add ("WAV", "Audio / WAV"); _MimeTypelist.add ("Wax", "Audio / X-MS-Wax"); _MimeTypelist.add (". Wbk", "Application / Msword"); _MimeTypelist.add ("

.wiz "," Application / Msword "); _MimeTypelist.add (". wm "," VIDEO / X-MS-WM); _MimeTypelist.add (". wma", "Audio / X-MS-WMA") _MimeTypelist.add (". Wmd", "Application / X-MS-WMD"); _MimeTypelist.add (". Wmv", "VIDEO / X-MS-WMV"); _MimeTypelist.add (". Wmx", "VIDEO / X-MS-WMX"); _MimeTypelist.add (". WMZ", "Application / X-MS-WMZ"); _MimeTypelist.add (". WPL", "Application / VND.MS-WPL") _MimeTypelist.add (". Wprj", "Application / Webzip"); _MimeTypelist.add (". Wsc", "text / scriptlet"); _MimeTypelist.add (". Wvx", "Video / X-MS-WVX "); _MimeTypelist.add (". Xbm "," image / x-xbitmap); _MimeTypelist.add (". Xdp", "application / vnd.adobe.xdp xml"); _MimeTypelist.add (". Xfd "," Application / Vnd.adobe.xfd XML "); _MimetyPelist.add (". xfdf "," application / vnd.adobe.xfdf "); _MimeTypelist.add (". xla "," Application / VND.MS " -excel "); _MimeTypelist.add (". xlb "," application / vnd.ms-excel "); _MimeTypelist.add (". xlc "," application / vnd.ms-excel "); _MimeTypelist.add (" .xld "," Application / VND.MS-Excel "); _MimeTypelist.a DD (". xlk", "Application / VND.MS-Excel"); _MimetyPelist.add (". xll", "Application / VND.MS-Excel"); _MimeTypelist.add (". xlm", "Application / VND.MS-Excel "); _MimeTypelist.add (". xls "," application / vnd.ms-excel "); _MimeTypelist.add (". xlt "," application / vnd.ms-excel "); _MimetyPelist. Add (". XLV", "Application / VND.MS-Excel");

_MimetyPelist.add (". Xlw", "Application / Vnd.ms-Excel"); _MimeTypelist.add (". Xml", "text / xml"); _MimeTypelist.add (". Xpl", "audio / scPLS" _MimeTypelist.add (". Xsl", "text / xml"); _MimeTypelist.add (". Z", "application / x-compress"); _MimeTypelist.add (". Zip", "Application / X- Zip-compressed ");} ///

returns the mime content-type for the support file extension /// string mime type (example: /" text / plain / ") public static string getMimetype (string string strfileExtension = new fileInfo (strfilename) .extension; string strcontenttype = null; bool mono = false;

if (MONO) {strContentType = MIMETypes.ContentType (strFileExtension);} else {Microsoft.Win32.RegistryKey extKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey (strFileExtension); strContentType = (string) extKey.GetValue ( "Content Type" }

if (! strContentType.ToString () = null) {return strContentType.ToString ();} else {return "application / octet-stream";}} catch (System.Exception) {return "application / octet-stream";} }

}

///

///// public class quotedcoding {/// /// zwraca Tablick Bajtow /// Zamienia 3 Znaki np '= a9' NA ODP Wartosc. /// zamienia '_' Na Znak 32 /// /// kupis_pawe = b3 /// kupis pawe? / returns> public Static Byte [] getByteArray (string s) {byte [] buffer = new byte [s.Length]; int bufferposition = 0; if (s.Length> 1) {for (int i = 0; i

BYTE [] NEWARRAY = New byte [bufferPosition]; array.copy (buffer, newarray); return newaRray;}

///

/// decoduje string "=? ISO-8859-2? q? kupis_pawe = b3? =" /// lub zakodowany base64 /// Na poprawny /// /// < Param name = "s"> "=? ISO-8859-2? q? kupis_pawe = b3? =" /// kupis pawe? / returns> public static string decodeone (string s) {char [] separator = {'?'}; string [] sarray = s.split (separator); if (SaRray [0] .Equals ("=") == false Return S;

Byte [] barray; // Rozpoznaj Rodzj Kodowania if (Sarray [2] .toupper () == "Q") // queryString Barray = GetByteArray (Sarray [3]); Else IF (Sarray [2] .toupper () == "B") // base64 bArray = Convert.FromBase64String (sArray [3]); else return s; // pobierz strone kodowa encoding encoding = Encoding.GetEncoding (sArray [1]); return encoding.GetString (bArray) } ///

/// decoduje string zamienia wpisy (=? ...? =) Na ODP Wartosci /// /// "ALA I =? ISO-8859-2? q? kupis_pawe = b3? = ma kota " /// " ALA I PAWE? Kupis ma kota " public static string decode (string s) {StringBuilder RetString = new stringbuilder (); int = 0, start = 0, stop; for (;;) {start = s.indexof ("=?", start); if (start == -1) {rettstring.Append S, OLD, S.LENGTH - OLD); Return RetString.toString ();} stop = s.indexof ("? =", start 2); if (stop == -1) // BLAD W STRINGU RETURN S S RetString.Append (s, OLD, START - OLD); RetString.Append (S.Substring (START, STOP - START 2)); start = stop 2; old = stop 2;}}

}

///

/// tnefattachment /// public class tnefattachment {#Region Member Variables

Private string _filename = ""; private long _fileLength = 0; private string _subject = ""; private bote [] _filecontent = null;

#ndregion

#Region Properties

///

/// attachment subject /// public string subject {get {return _subject;} set {_subject = value;}} /// /// attachment file length //// / public long longlength {get {return _fileLength;} set {_filelength = value;}}

///

/// attachment file name /// public string filename {get {return_filename;} set {_filename = value;}}

///

/// attachment file content /// public byte [] filecontent {get {return_filecontent;} set {_filecontent = value;}}

#ndregion

Public tnefattachment () {}

~ Tnefattachment () {_filecontent = null;}}

///

/// OpenPop.mimeParser.tnefParser /// public class tnefparser {#Region Member Variables

private const int TNEF_SIGNATURE = 0x223e9f78; private const int LVL_MESSAGE = 0x01; private const int LVL_ATTACHMENT = 0x02; private const int _string = 0x00010000; private const int _BYTE = 0x00060000; private const int _WORD = 0x00070000; private const int _DWORD = 0x00080000;

private const int AVERSION = (_DWORD | 0x9006); private const int AMCLASS = (_WORD | 0x8008); private const int ASUBJECT = (_DWORD | 0x8004); private const int AFILENAME = (_string | 0x8010); private const int ATTACHDATA = ( _Byte | 0x800F);

Private stream fstnef; private hashtable _attachments = new hashtable (); private tnefattachment _attachment = null;

private bool _verbose = false; // private string _logFile = "OpenPOP.TNEF.log"; private string _basePath = null; private int _skipSignature = 0; private bool _searchSignature = false; private long _offset = 0; private long _fileLength = 0; Private string _tneffile = ""; private string strsubject; #ndregion

#Region Properties

// public string logfilepath // {// get {return _logfile;} // set {_logfile = value;} //}

Public string tneffile {get {return_tneffile;} set {_tneffile = value;}}

Public Bool Verbose {Get {Return_Verbose;} set {_verbose = value;}}

Public string basepath {get {return_basepath;} set {try {f (value.endswith ("//")) _basepath = value; else _basepath = value "//";} catch {}}}

Public int skipsignature {get {return _skipsignature;} set {_skipsignature = value;}}

Public Bool SearchSignature {Get {Return_SearchSignature;} set {_searchSignature = value;}}

Public long offset {get {return _offset;} set {_offset = value;}}

#ndregion

Private int getint32 (byte [] p) {RETURN (P [0] (p [1] << 8) (p [2] << 16) (p [3] << 24));}

Private short getint16 (byte [] p) {return (p [0] (p [1] << 8));}

Private Int geti32 () {byte [] buf = new byte [4];

IF (streamreadbytes (buf, 4)! = 1) {utility.loGerror ("Geti32 (): unExpected end of infut / n"); Return 1;} Return GetInt32 (BUF);

Private int geti16 () {byte [] buf = new byte [2]; if (streamreadBytes (buf, 2)! = 1) {utility.loGerror ("geti16 (): undexpected end of infut / n"); return 1 } Return GetInt16 (BUF);

Private Int geti8 () {byte [] buf = new byte [1];

IF (streamreadbytes (buf, 1)! = 1) {utility.loGerror ("geti8 (): undexpected end of infut / n"); return 1;} return (int) buf [0];}

Private Int streamreadBytes (byte [] buffer, int size) {try {if (fstnef.position size <= _filelength) {fstnef.read (buffer, 0, size); return 1;} else return 0;} catch (Exception e) {utility.loGerror ("streamreadbytes ():" E.MESSAGE); RETURN 0;}}

Private void closetnefstream () {Try {fstnef.close ();} catch (exception e) {utility.loGerror ("ClosetNefStream ():" E.MESSAGE);}

///

/// Open THE MS-TNEF Stream from file /// /// MS-TNEF file /// < / RETURns> Public Bool OpenTnefStream (String Strfile) {//utility.logfilepath=logfilepath;

TNEFFile = strFile; try {fsTNEF = new FileStream (strFile, FileMode.Open, FileAccess.Read); FileInfo fi = new FileInfo (strFile); _fileLength = fi.Length; fi = null; return true;} catch (Exception e) {UTILITY.LOGERROR ("OpenTnefStream (file):" E.MESSAGE); RETURN FALSE;}}

///

/// open the ms-tnef stream from bytes /// /// ms-tnef bytes /// < / returns> public bool OpenTNEFStream (byte [] bytContents) {//Utility.LogFilePath=LogFilePath;try {fsTNEF = new MemoryStream (bytContents); _fileLength = bytContents.Length; return true;} catch (Exception e) {Utility.LogError ("OpenTnefStream (bytes):" E.MESSAGE); RETURN FALSE;}}

///

/// Find the MS-Tnef Signature /// /// True if found, Vice Versa public bool findsignature () {bool return = false; long LPOS = 0;

INT D;

Try {for (LPOS = 0 ;; LPOS ) {IF (fstnef.seek (lpos, seekorigin.begin) == -1) {PrintResult ("no signature found / n"); return false;}

D = Geti32 (); if (d == Tnef_signature) {PrintResult ("Signature Found at {0} / n", lpos); Break;}} Ret = true;} catch (Exception E) {Utility.loGerror (" FINDSIGNATURE (): " E.MESSAGE); RET = false;}

Fstnef.position = lpos;

Return Ret;}

Private void decode_attribute (int d) {byte [] buf = new byte [4000]; int Len; intv; int 1;

LEN = Geti32 (); / * data length * /

Switch (D & 0xFFFF0000) {Case_Byte: PrintResult ("Attribute {0} =", D & 0xFFFF); for (i = 0; i

IF (i <10) PrintResult ("{0}", v); ELSE IF (i == 10) PrintResult ("...");} printresult ("/ n"); Break; Case_Word: PrintResult "Attribute {0} =", D & 0xFFFF); for (i = 0; i

PrintResult ("Attribute {0} = {1} / n", D & 0xfff, Encoding.default.getstring (buf)); Break; Default: streamreadbytes (buf, len); PrintResult ("Attribute {0} / n" , D); Break;}

Geti16 (); / * checksum * /}

PRIVATE VOID DECODE_MESSAGE () {INT D;

D = Geti32 ();

Decode_attribute (d);

Private void decode_attachment () {byte [] buf = new byte [4096]; int Len; Int i, chunk;

D = Geti32 ();

Switch (d) {case asubject: len = geti32 ();

StreamReadBytes (buf, len);

Byte [] _SUBJECTBUFFER = New Byte [LEN - 1];

Array.copy (BUF, _SUBJECTBUFFER, (long) LEN - 1);

STRSUBJECT = Encoding.default.getstring (_SUBjectBuffer);

PrintResult ("Found Subject: {0}", strsubject);

Geti16 (); / * checksum * /

Break;

Case AfileName: LEN = Geti32 (); StreamReadbytes (BUF, LEN); // PrintResult ("file-name: {0} / n", buf); BYTE [] _filenamebuffer = new byte [len - 1]; array. Copy (buf, _fileNameBuffer, (long) len - 1); if (_fileNameBuffer == null) _fileNameBuffer = Encoding.Default.GetBytes ( "tnef.dat"); string strFileName = Encoding.Default.GetString (_fileNameBuffer);

PrintResult ("{0}: Writing {1} / n", basepath, strfilename;

// new attachment found because attachment data goes before attachment name _attachment.FileName = strFileName; _attachment.Subject = strSubject; _attachments.Add (_attachment.FileName, _attachment);

Geti16 (); / * checksum * /

Break;

Case attachdata: len = Geti32 (); PrintResult ("attach-data: {0} bytes / n", len)

_ttachment = new tnefattachment (); _ttachment.filecontent = new byte [len]; _ttachment.fileLength = LEN;

For (i = 0; i buf.length) chunk = buf.length;

StreamReadBytes (buf, chunk);

Array.copy (buf, 0, _attachment.filecontent, i, chun);

i = chunk;}

Geti16 (); / * checksum * /

Break;

DEFAULT: DECODE_ATRIBUTE (D); Break;}}

///

/// Decoded attachments /// /// attachment array public hashtable attachments () {return _attachments;}

///

/// save all decoded attachments to files /// /// true is succeded, vice versa public bool SaveAttachments () {bool blnRet = false; IDictionaryEnumerator Ideattachments = _attachments.getenumerator ();

While (ideattachments.movenext ()) {blnret = saveattachment (tnefattachment) deattachments.value);} return blnret;}

///

/// save a decoded attachment to file /// ///

///

/// PARSE MS-TNEF Stream /// /// True is sucpeded, vice versa public bool parse () {byte [] buf = new byte [4]; int D;

IF (FindSignature () {if (Skipsignaature <2) {d = Geti32 (); if (Skipsignature <1) {IF (D! = Tnef_Signature) {PrintResult ("Seems Not to Be a Tnef File / N); Return false;}}}

D = Geti16 (); PrintResult ("Tnef Key IS: {0} / N", D); for (;;) {IF (streamreadBytes (buf, 1) == 0) Break;

D = (int) BUF [0];

switch (d) {case LVL_MESSAGE: PrintResult ( "{0}: Decoding Message Attributes / n", fsTNEF.Position); decode_message (); break; case LVL_ATTACHMENT: PrintResult ( "Decoding Attachment / n"); decode_attachment (); break; default: PrintResult ( "Coding Error in TNEF file / n"); return false;}} return true;} else return false;} private void PrintResult (string strResult, params object [] strContent) {string strRet = string. Format (strresult, strcontent); if (verbose) uTility.loGerror (STRRET);

~ Tnefparser () {_attachments = null; closetnefstream ();

Public tnefparser ()}

///

//////// /// ms-tnef file public tnefparser (String string) { OpenTnefstream (Strfile);

///

//////// /// ms-tnef bytes public tnefparser (byte [] ByTContents) {OpenTnefStream (ByTContents);}}

///

/// Summary description for utility. /// public class utility {private static bool m_blnlog = false; private static string m_strlogfile = "openpop.log";

Public utility () {}

// public static string [] SplitText (string strText, string strSplitter) // {// string [] segments = new string [0]; // int indexOfstrSplitter = strText.IndexOf (strSplitter); // if (indexOfstrSplitter =! -1) // {////} // return segments; //} //

///

/// verifies WHETHER THE FILE IS OF PICTURE TYPE or NOT / / / /// file to be verified /// TRUE IF PICTURE FILE, FALSE IF NOTURE FILE, FALSE IF ISPICTUREFILE (STRFILE! = NULL && STRFILE! = ") {Strfile = strfile.tolower (); if (strfile) {strfile = strfile.tolower (); if (Strfile). Endswith (". JPG") || Strfile.endSwith (". BMP") || Strfile.endSwith (". Ico") || Strfile.endSwith (". Gif") || Strfile.endSwith (". PNG" )) RETURN TRUE; Else Return False;} carat}}}}}}} /// /// Parse Date Time Info from mime header /// /// Encoded MIME date time /// Decoded date time info public static string ParseEmailDate (string strDate) {string strRet = strDate.Trim (); int indexOfTag = strRet .Indexof (","); if (indexoftag! = -1) {strret = strret.substring (IndexoftAg 1);

Strret = quotetext (strret, " "); strret = quottext (strret, "-"); strret = quotetext (strret, "gmt"); strret = quottext (strret, "cst"); return strret.trim () }

///

/// quote the text accounting to a tag /// /// text to be quote /// Quote tag /// Quoted Text public static string QuoteText (string strText, string strTag) {int indexOfTag = strText.IndexOf (strTag);! if (indexOfTag = -1 Return strText.Substring (0, indexoftag - 1); else return strtext;} /// /// PARSE file name from mime header /// /// MIME header /// Decoded file name public static string ParseFileName (string strHeader) {string strTag; strTag = "filename =";. int intPos = strHeader.ToLower () IndexOf ( STRTAG); if (intpos == -1) {stragg = "name ="; intpos = strheader.tolower (). Indexof (start; if (intpos! = -1) {strret = strheader.substring (INTPOS STRTAG.LENGTH); INTPOS = Strret.tolower (). Indexof (";"); if (intpos! = -1) Strret = Strret .SUBSTRING (1, INTPOS - 1); strret = remove bete (strret);} else strret = ""

Return Strret;

///

/// PARSE Email Address from mime header /// /// mime header /// Decoded user name /// Decoded email address /// True if decoding succeeded, false if failed public static bool ParseEmailAddress (string strEmailAddress , ref string strUser, ref string strAddress) {int indexOfAB = strEmailAddress.Trim () LastIndexOf (. "<"); int indexOfEndAB = strEmailAddress.Trim () LastIndexOf (. ">"); strUser = strEmailAddress; strAddress = strEmailAddress; IF (indexofab> = 0 && indexofendab> = 0) {ifxofab> 0) {struser = struser.substring (0, indexofab - 1); // struse = struser.substring (0, indexofaB-1) .trim ( '/ "); // if (struser.indexof (" / ")> = 0) // {// struser = struser.substring (1, struser.Length-1); //}} Struser = Struser .Trim (); struser = struser.trim ('/ "); straddress = strad Dress.substring (indexofab 1, indexofendab - (indexofab 1));} struser = struset.trim (); struse = decodeExt (struser); straddress = straddress.trim (); return true;}

///

/// Save Byte Content to a file /// /// file to be saved to /// byte array content /// True if saving succeeded, false if failed public static bool SaveByteContentToFile (string strFile, byte [] bytContent) {try {if (File.Exists ( Strfile)) File.Delete (Strfile); filestream fs = file.create (strfile); fs.write (byTcontent.Length); fs.close (); return true;} catch (Exception E) {Utility .Logerror ("SavebyteContentTOfile ():" E.MESSAGE); RETURN FALSE;}} /// /// Save text Content to a file /// /// File to be saved to /// text content ///

///

/// r /// file to be read from /// Read text content /// True if reading succeeded, false if failed public static bool ReadPlainTextFromFile (string strFile, ref string strText) {if (File.Exists (strFile)) {Streamreader fs = new streamreader (strfile); strText = fs.readToend (); fs.close (); return true;} else returnaf false;} /// /// sepearte header name and header value ///// / /// /// public static string [] getHeadersValue (String Strrawheader) {if (Strrawheader == NULL) Throw new Argumentnullexception ("Strrawheader", "Argument Was Null";

String [] array = new string [2] {"", "}; int indexofcolon = STRRRAWHeader.indexof (": ");

Try {Array [0] = STRRAWHeader.Substring (0, indexofcolon) .trim (); array [1] = strrawheader.substring (INDEXOFCOLON 1) .trim ();} catch (exception) {}

Return array;

///

/// Get quoted text /// /// text with quotes /// target tag /// text without quote public static string getquotedValue (string string string strsplitter, string stratag) {ix ( strText == null) throw new ArgumentNullException ( "strText", "Argument was null"); string [] array = new string [2] { "", ""}; int indexOfstrSplitter = strText.IndexOf (strSplitter);

Try {Array [0] = strText.Substring (0, indexofstrsplitter) .trim (); array [1] = strText.Substring (INDEXOFSTRSPLITTER 1) .trim (); int pos = array [1] .indexof ("/ ""); If (pOS! = -1) {INT POS2 = array [1] .indexof ("/", pOS 1); array [1] = array [1] .substring (POS 1, POS2 - POS - 1);}} catch (exception) {}

// Return Array; IF (Array [0] .tolower () == start () Return Array [1] .trim (); else return null;

/ * String [] array = null; try {array = regex.split (strText, strsplitter); // return array; if (Array [0] .tolower () == start.tolower ()) Return Removequote (array [ 1] .trim ()); else return null;} catch {return null;} * /}

///

/// /// Source Encode Text /// New Charset /// Encoded text with new charset public static string Change (string strText, string strCharset) {if (strCharset == null || strCharset == "") return strText; byte [ ] b = encoding.default.getbytes (start); Return New String (Str000) .getchars (b));} /// /// Remove Non-Standard Base 64 Characters /// < / Summary> /// source text /// Standard base 64 text public static string removenonb64 (string string) {return strText.replace ("/ 0 "," ");

///

///// /// Source text /// text with white blanks Public Static String RemoveWhiteBlanks (String Strtext) {Return strText.Replace ("/ 0", "") .REPLACE ("/ r / n", ");}

///

/// Remove quotes /// /// text with quotes /// text without quotes public STATIC STRING RemoveQuote (string strret = strText; if (strret.startswith ("/")) Strret = strret.substring (1); if (strret.endswith ("/")) Strret = Strret. Substring (0, Strret.length - 1); Return Strret;

///

/// Decode One line of text /// /// Encoded text /// decoded text Public static string decodeline (reburn decodetext (transovewhiteblanks (strovewhiteblanks (strovewhiteblanks (strtext));} /// /// Verifies Wether TEXT IS a Valid Mime Text or Not /// /// < param name = "strText"> text to be verified /// True if MIME text, false if not private static bool IsValidMIMEText (string strText) {int intPos = strText.IndexOf ( " =? "); Return (INTPOS! = -1 && start.indexof ("? = ", Intpos 6)! = -1 && start.length> 7);

///

/// Decode text /// /// Source text /// decoded text public static String DecodeText (String Strtext) {/ * try {string string strret = ""; string strbody = "; matchcollection mc = regex.matches (strtext, @" / = /? (? / s ) /? (? < Encoding> / w) /? (? / s ) /? / = ");

For (int i = 0; i

Switch (MC [i] .Groups ["eNCoding"]. value.toupper ()) {CASE "B": strbody = decodeb64s (strbody, mc [i] .Groups ["charset"]. value); Break; Case "Q": strbody = decodeqp.convertHexContent (strbody); //, m.Groups ["charset"]. Value); break; default: break;} strret = strbody;} else {strret = mc [i] .value ;}}}}} Catch {return strret;} * / try {string Strret = ""; string [] strparts = regex.split (string strbody = "; const string Strregex = @ "/ = /? (? / w) /? (? / s ) /? / ="; match m = null;

For (int i = 0; i

Switch (M.Groups ["Encoding"]. Value.toupper ()) {CASE "B": strbody = decodeb64s (strbody, m.Groups ["charset"]. value); break; case "q": strbody = Decodeqp.convertHexContent (strbody); //, m.Groups ["charset"]. Value); break; default: break;} strret = strbody;} else {if (! IsvalidMimetext (strparts [i])) STRET = StrParts [i]; else {// blank text}}} Return Strret;} catCh {return strt;

/ * {Try {if (strText! = Null && strText! = ") {If (isvalidmimetext) {// position at the end of charset int id = strText.indexof (" =? "); Int idos2 = strText .Indexof ("?", INTPOS 2); if (INTPOS2> 3) {string strcharset = strText.Substring (2, INTPOS2-2); string strencoding = strText.Substring (intPos2 1, 1); int INTPOS3 = STRTEXT.INDEXOF ("? =", intpos2 3); string strBody = strText.Substring (intpos2 3, intpos3-intpos2-3); string strhead = ""; if (intpos> 0) {strhead = strText.substring (0, INTPOS-1);} String Strend = ""; if (intpos3

///

////// /// /// public static string decodeb64s (string stringstext) { return Encoding.Default.GetString (deCodeB64 (strText));} public static string deCodeB64s (string strText, string strEncoding) {try {if (strEncoding.ToLower () == "ISO-8859-1" .ToLower ()) return DecodeB64S (Strtext); Else Return Encoding.Getencoding (Strencoding) .getstring (DecodeB64 (Strtext));} catCh {return decodeb64s (strtext);}}

Private static byte [] decodeb64 (string string) {byte [] by = null; try {ifxt! = "") {by = convert.FromBase64String (strTrtext); //strtext ioncoding.default.getstring(BY) ;}}} Catch (Exception E) {by = encoding.default.getbytes ("/ 0"); LOGERROR ("DecodeB64 ():" E.MESSAGE);} Return By;

///

/// Turns file logging on and off. /// /// Comming soon. public static bool log {get {return m_blnlog;} set {m_blnlog = Value;}}

internal static void LogError (string strText) {// Log = true; if (Log) {FileInfo file = null; FileStream fs = null; StreamWriter sw = null; try {file = new FileInfo (m_strLogFile); sw = file.AppendText (); // fs = new filestream (m_strlogfile, filemode.openorcreate, fileaccess.write); // sw = new streamwriter (fs); sw.writeLine (datetime.now); sw.writeline ("/ r / n"); sw.flush ();} finally {if (sw! = null) {sw = null;} if (fs! = null) {fs.close () ; Fs = null;}}}}

Public static bool isquotedprintable (string strText) {if (string! = null) Return (strText.tolower () == "quoted-printable" .tolower ()); else returnaf false;}

Public Static Bool IsBase64 (STRTEXT! = NULL) Return (strText.tolower () == "Base64" .tolower ()); else return false;}

Public static string [] splitonsemicolon (string string) {if (string == null) Throw new ArgumentnullException ("strunt", "argument was null);

String [] array = null; int indexofcolon = strText.indexof (";");

IF (indexofcolon <0) {array = new string [1]; array [0] = string; return array;} else {array = new string [2];

Try {Array [0] = strText.Substring (0, indexofcolon) .trim (); array [1] = strTexoft.Substring (INDEXOFCOLON 1) .trim ();} catch (exception) {}

Return array;

public static bool IsNotNullText (string strText) {try {return (null && strText strText = = ""!!);} catch {return false;}} public static bool IsNotNullTextEx (string strText) {try {return (strText = null! && strText.trim ()! = "");} catch {return false;}}

Public Static Bool ISORNULLTEXTEXTEX (STRTEXT == Null || strText.trim () == "";} catch} catch {returnaf false;}}

}

}

namespace OpenPOP.POP3 {using System; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Net.Sockets; using System.Security.Cryptography; using System.Threading;

///

/// Possible responses received from the server when performing an Authentication /// public enum AuthenticationResponse {/// /// Authentication succeeded /// SUCCESS = 0, /// /// login doesn't exist on the pop3 server /// invaliduser = 1, /// /// Password is invalid for the give login /// invalidpassword = 2, /// /// invalid login and / or password /// invaliduserpassword = 3}

///

//// /// Tryboth means code will first attempt by using apop method as its more secure. /// in case of fiveure the code will fall back to uSERPASS method. /// public enum AuthenticationMethod {/// /// Authenticate using the USER / PASS method. USER / PASS is secure but all POP3 servers may not support this method / // Userpass = 0, /// /// Authenticate Using the apop method /// apop = 1, /// /// Authenticate Using user / pass. In Case User / Pass Fails Then Revert to ApoP /// Tryboth = 2} /// /// Thrown When The Pop3 Server Sends An Error (-ERR) DURING INTIAL HANDSHAKE (HELO) // / public class popserverNotavailableException: Exception {}

///

/// thrown when the specified pop3 server can not be found in contnected with /// public class popserverNotFoundException: Exception {}

///

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////> > Public Class AttachmentencodingNotSupportedException: Exception {}

///

/// thrtown when supplied login doesn't exist on the server /// /// SHOULD BE Used Only When User / Pass Authentication Method PUBLIC Class InvalidLoginexception: Exception {}

///

/// Thrown when the password supplied for the login is invalid /// /// Should be used only when using USER / PASS Authentication Method public class InvalidPasswordException : Exception {} /// /// Thrown When Either the login or the password is invalid on the pop3 server /// ///// SHOULD BE USED Only WHEN Using APOP Authentication method public class invalidloginorpasswordException: exception {}

///

/// Thrown when the user mailbox is in a locked state /// /// The mail boxes are locked when an existing session is open on the mail server. Lock conditions Are Also Met in Case of Aborted Sessions Public Class PopserverLockexception: Exception {}

///

/// Summary description for MyMD5 /// public class MyMD5 {public static string GetMD5Hash (String input) {MD5 md5 = new MD5CryptoServiceProvider ();. // the GetBytes method returns byte array Equavalent of a string Byte [] res = md5.computehash (input), 0, input.length; char [] temp = new char [res. generation]; // Copy to a char Array Which Can Be Passed to A String Constructor System.Array.copy (RES, TEMP, RES.LENGTH); // Return The Result As a string return new string (temp);

public static string GetMD5HashHex (String input) {MD5 md5 = new MD5CryptoServiceProvider (); DES des = new DESCryptoServiceProvider (); // the GetBytes method returns byte array equavalent of a string byte [] res = md5.ComputeHash (Encoding.Default. Gettes (Input), 0, Input.Length;

String returnthis = ""; for (int i = 0; i

Return Returnthis;

}

}

///

/// Popclient /// /// Event That Fires When to Connect with Target Pop3 Server. /// public Event EventHandler CommunicationBegan;

///

/// Event That Fires When Connected with Target Pop3 Server. /// public evenet athandler communicationoccade;

///

/// Event That Fires When disconnected with target pop3 server. /// public evenethandler communicationLost;

///

/// Event That Fires When Authentication Began with Target Pop3 Server. /// public evenethandler authenticationbegan

///

/// Event That Fires When Authentication Finished with Target Pop3 Server. /// public evenethandler automationfinished;

///

/// Event tria Fires When Message Transfer Has Begun. /// public evenet athandler messagetransferbegan

///

/// Event tria Fires When Message Transfer Has Finished. /// public event Eventhandler MessageTransferfinished;

INTERNAL VOID ONCOMMUNICATIONBEGAN (Eventargs E) {IF (CommunicationBegan! = NULL) CommunicationBegan (this, e);}

INTERNAL VOID OnCommunicationOccured (Eventargs E) {if (CommunicationOccured! = NULL) CommunicationOccured (this, e);}

internal void OnCommunicationLost (EventArgs e) {if (CommunicationLost = null!) CommunicationLost (this, e);} internal void OnAuthenticationBegan (EventArgs e) {if (AuthenticationBegan = null!) AuthenticationBegan (this, e);}

INTERNAL VOID ONAUTHENTICATIONFINIShed (Eventargs E) {IF (AuthenticationFinished! = NULL) AuthenticationFinished (this, e);}

INTERNAL VOID OnMessageTransferbegan (Eventargs E) {IF (MessageTransferbegan! = NULL) MessageTransferbegan (this, e);}

INTERNAL VOID OnMESSAGETRANSFERFINISHED (EventArgs E) {IF (MessageTransferfinished! = null) MessageTransferfinished (this, e);}

private const string RESPONSE_OK = " OK"; // private const string RESPONSE_ERR = "- ERR"; private TcpClient clientSocket = null; private StreamReader reader; private StreamWriter writer; private string _Error = ""; private int _receiveTimeOut = 60000; private int _sendTimeOut = 60000; private int _receiveBufferSize = 4090; private int _sendBufferSize = 4090; private string _basePath = null; private bool _receiveFinish = false; private bool _autoDecodeMSTNEF = true; private int _waitForResponseInterval = 200; private int _receiveContentSleepInterval = 100; private string _aPOPTimestamp Private string _lastcommandResponse; private bool _connected = true;

Public Bool Connected {Get {Return_Connected;}}

Public string apoptimestamp {get {return _apoptimestamp;}}

///

/// receive content sleep interval /// public int ReceiveContentSleepInterval {get {return _receiveContentSleepInterval;} set {_receiveContentSleepInterval = value;}} /// /// wait for response Interval /// public int waitingforrespondinterval {get {return_waitforrespondsponseinterval;} set {_WaitforResponseinterval = value;}}

///

/// WHETHER AUTO DECODING MS-TNEF Attachment Files /// Public Bool Autodecodemstnef {Get {Return_autodecodemstnef;} set {_autocEMStnef = value;}}

///

/// path to extract ms-tnef attachment files /// public string basepath {get {return _basepath;} set {try {i (value.endswith ("//")))) _basepath = value; else _basepath = value "//";} catch {}}}

///

/// Receive timeout for the connection to the SMTP server in milliseconds /// The default value is 60000 milliseconds /// public int ReceiveTimeOut {get {return _receiveTimeOut;..} Set { _ReceiveTimeout = value;}}

///

/// Send timeout for the connection to the SMTP server in milliseconds /// The default value is 60000 milliseconds /// public int SendTimeOut {get {return _sendTimeOut;..} Set { _sendtimeout = value;}}

///

/// Receive buffer size /// public int ReceiveBufferSize {get {return _receiveBufferSize;} set {_receiveBufferSize = value;}} /// /// Send buffer size / // public int sendbuffersize {get {return _sendbuffersize;} set {_sendBuffersize = value;}}

Private Void WaitforResponse (Bool BlNCondiction, INTINTERVAL) {if (INTINTERVAL == 0) INTINTERVAL = WaitforResponseInterval; while (! blncondiction == true) {thread.sleep (intInterval);}}

private void WaitForResponse (ref StreamReader rdReader, int intInterval) {if (intInterval == 0) intInterval = WaitForResponseInterval;! //while(rdReader.Peek()==-1 || rdReader.BaseStream.CanRead) while (rdReader!. BaseStream.canread) {thread.sleep (intinterval);}

private void WaitForResponse (ref StreamReader rdReader) {DateTime dtStart = DateTime.Now; TimeSpan tsSpan; while (rdReader.BaseStream.CanRead!) {tsSpan = DateTime.Now.Subtract (dtStart); if (tsSpan.Milliseconds> _receiveTimeOut) break; Thread.Sleep (_WaitforResponseInterval);}}

private void WaitForResponse (ref StreamWriter wrWriter, int intInterval) {if (intInterval == 0) intInterval = WaitForResponseInterval; while (! wrWriter.BaseStream.CanWrite) {Thread.Sleep (intInterval);}}

///

//////////////// /// string to examine private void ExtractApopTimestamp (string strResponse) {match match = Regex.Match (strResponse, "< >."); if (match.Success) {_aPOPTimestamp = match.Value ;}}} /// Tests a string to see if it's a " ok" string /// /// string to example /// True if Response is an " OK" string

///

/// Get Response content /// /// string to example /// Response content private String getResponseContent () {return_lastcommandresponse.substring (3);

///

/// senends a command to the pop server. /// /// Do not give error /// true if server responded " OK" private bool SendCommand (string strCommand, bool blnSilent) {_lastCommandResponse = ""; try {if (writer.BaseStream.CanWrite) {writer.WriteLine (strCommand); writer.Flush (); // WaitForResponse (ref reader, WaitForResponseInterval); WaitForResponse (ref reader); _lastCommandResponse = reader.ReadLine (); return IsOkResponse (_lastCommandResponse) Else Return false;} catch (exception e) {if (! Blnsilent) {_ERROR = STRCOMMAND ":" E.MESSAGE; uTility.loGerror (_ERROR);}}}}}}} /// /// sends a command to the pop server. /// /// Command to send to server /// True IF server responded OK "

///

/// seneds a command to the pop server, expects an integer reply in the response /// /// /// castruct new popclient //// public popclient () {uTility.log = false;}

///

/// Construct new POPClient /// public POPClient (string strHost, int intPort, string strlogin, string strPassword, AuthenticationMethod authenticationMethod) {Connect (strHost, intPort); Authenticate (strlogin, strPassword AuthenticationMethod;

///

///connect to remove server /// /// pop3 host /// POP3 port public void connect (string strhost, int intport) {oncommunicationbegan (evenetargs.empty);

clientSocket = new TcpClient (); clientSocket.ReceiveTimeout = _receiveTimeOut; clientSocket.SendTimeout = _sendTimeOut; clientSocket.ReceiveBufferSize = _receiveBufferSize; clientSocket.SendBufferSize = _sendBufferSize;

try {clientSocket.Connect (strHost, intPort);} catch (SocketException e) {Disconnect (); Utility.LogError ( "Connect ():" e.Message); throw new PopServerNotFoundException ();} reader = new StreamReader ( ClientSocket.getStream (), encoding.default, true); writer = new streamwriter ()); Writer.autoflush = true;

WaitForResponse (Ref Reader, WaitforResponseInterval);

String strresponse = reader.readline ();

if (IsOkResponse (strResponse)) {ExtractApopTimestamp (strResponse); _connected = true; OnCommunicationOccured (EventArgs.Empty);} else {Disconnect (); Utility.LogError ( "Connect ():" "Error when login, maybe POP3 server NOT EXIST "); throw new popserverNotavailableException ();}}

///

/// Disconnect from POP3 server /// public void Disconnect () {try {clientSocket.ReceiveTimeout = 500; clientSocket.SendTimeout = 500; SendCommand ( "QUIT", true); clientSocket .ReceiveTimeout = _receiveTimeOut; clientSocket.SendTimeout = _sendTimeOut; reader.Close (); writer.Close ();. clientSocket.GetStream () Close (); clientSocket.Close ();} catch {//Utility.LogError("Disconnect (): " E.MESSAGE);} Finally {Reader = NULL; Writer = NULL; ClientSocket = NULL;} oncommunicationLost (Eventargs.empty);}

///

/// Release me /// ~ popclient () {disconnect ();

///

///// /// user name /// Password < / param> public void Authenticate (string strlogin, string strPassword) {Authenticate (strlogin, strPassword, AuthenticationMethod.USERPASS);} /// /// verify user and password /// /// < Param name = "strlogin"> user name /// strpassword ///

///

///// /// user name /// Password < / param> private void AuthenticateUsingUSER (string strlogin, string strPassword) {OnAuthenticationBegan (EventArgs.Empty); if (SendCommand ( "USER" strlogin)!) {Utility.LogError ( "AuthenticateUsingUSER (): wrong user"); throw new INVALIDLOGINEXCEPTION ();

WaitForResponse (Ref Writer, WaitforResponseInterval);

IF ("Pass" strpassword) {if (_lastcommandResponse.tolower (). Indexof ("Lock")! = -1) {Utility.loGerror ("AuthenticateusingUser (): Maildrop is locked"; throw new POPSERVERLOCKEXCEPTION ();} else {utility.loGerror ("AuthenticateusingUser (): wrong password or" getRESPONSECONTENT (); throw new invalidpasswordException ();}}

OnauthenticationFinished (EventArgs.empty);

///

/// verify user and password using apop /// /// user name /// Password Private void Authenticateusingapop (String Strlogin, String strpassword) {onauthenticationBegan (Eventargs.empty);

if (! SendCommand ( "APOP" strlogin "" MyMD5.GetMD5HashHex (strPassword))) {Utility.LogError ( "AuthenticateUsingAPOP (): wrong user or password"); throw new InvalidLoginOrPasswordException ();}

OnauthenticationFinished (EventArgs.empty);

/ * Private string getcommand (string infut) {try {return INPUT.SPLIT ('') [0];} catch (exception e) {utility.loGerror ("getcommand ():" E.MESSAGE); Return "" }} * / Private string [] getParameters (String INPUT) {String [] Temp = INPUT.SPLIT (''); string [] retstringArray = new string [Temp.Length - 1]; array.copy (Temp, 1 , RetstringArray, 0, Temp.length - 1);

Return RetstringArray;

///

/// Get Message Count /// /// Message Count public int getMessageCount () {Return SendcommandintResponse ("stat");}

///

/// deletes message with given index when close () is caled /// /// public bool deleteMessage (int int INTMESSAGEINDEX) { Return SendCommand ("dele" intMessageIndex.toString ());

///

/// deletes messages /// public bool deleteAllMessages () {int messagecount = getMessageCount (); for (int messageItem = messagecount; messageItem> 0; messageageItem -) {= DeleteMessage (MessageItem)) Return False;} Return True;

///

/// quit pop3 server /// public bool quit () {return sendcommand ("quit");}

///

/// Keep Server Active /// public bool noP () {Return Sendcommand ("NOOP");

///

/// Keep Server Active /// public bool rset () {Return SendCommand ("Rset");}

///

/// Identify User /// public bool user () {return sendcommand ("user");}

///

/// Get Messages Info /// ///

// Modify by Playyuer $ AT $ microshaoft.com mimeParser.MESSAGE MSG = FetchMessage (IntMessagenumber, "TOP {0} 0", TRUE);

OnmessageTransferfinished (Eventargs.empty);

Return msg;

///

/// Get Message Uid /// /// Message Number public string getMessageUid (int int int measureageUMber) {string [] string [] str remote = null ; If ("UIDL" INTMESSAGENUMBER.TOSTRING ())) {Strvalues ​​= getParameters (_lastcommandResponse);} return strvalues ​​[1];}

///

/// Get Message UIDS /// public arraylist getMessageuids () {ArrayList UIDS = New ArrayList (); if (SendCommand ("UIDL") {string strresponse = reader.readline WHILE (Strresponse! = ") {Uids.add (strretponse.split (') [1]); strretponse = reader.readline ();} return uids;} else {return null;}}

///

/// Get the Sizes of all the message /// CAUTION: Assumes no Messages Have Been Deleted /// /// size of each message public arraylist List () {arraylist (); if (SendCommand ("List")) {string strresponse = reader.readLine (); while (Strresponse! = ") {Sizes.add (int.parse .Split ('') [1]))); strretponse = reader.readline ();} returnizes;} else {return null;}} /// /// Get the size of a message ///// /// message number /// Size of message public int LIST (int intMessageNumber) {return SendCommandIntResponse ( "LIST" intMessageNumber .Tostring ());

// Add by Playyuer $ AT $ Microshaoft.com Public Delegate Void DataEventhandler (int messageid, int data);

Public Event DataEventHandler DataArrival;

Public void OnMessageReceiving (int messageid, int data) {if (dataarrival! = null) {dataArrival (messageid, data);}

///

/// read stream content /// /// length of content to read /// content /// private string receivecontent (int messageid, int idtent "{string strresponse = null; stringbuilder builder = new stringbuilder ();

WaitForResponse (Ref Reader, WaitforResponseInterval);

Strresponse = reader.readLine (); int = 0; int = 0; // add by Playyuer $ AT $ microshaoft.com onmesereceiving (messageid, intlen); while (strretsponse! = ".") // || INTLEN

// Add by Playyuer $ AT $ microshaoft.com onMessageReceiving (MessageID, intlen);

WaitforResponse (Ref Reader, 1);

Strresponse = reader.readLine (); if (INTLINES% _ReceiveContentsleepinterval) == 0) // Make An Interval Pause To EnSure Response from Server Thread.Sleep (1);

OnMessageReceiving (MessageID, -1); // Receive an email

Builder.Append (Strresponse "/ R / N");

Return builder.toString ();

}

///

/// Get Message Info /// /// Message Number on server /// message object Public mimeParser.Message getMessage (int INTNUMBER, BOOL BLNONLYHEADER) {OnMessageTransferbegan (Eventargs.empty);

// modify by Playyuer $ AT $ microshaoft.com mimeParser.Mestage MSG = FetchMessage (INTNUMBER, "Retr {0}", BLNONLYHEADER);

OnmessageTransferfinished (Eventargs.empty);

Return msg;

///

/// fetches a message or a message header /// /// Command to send to pop server /// Only return message header /// Message object public MIMEParser.Message FetchMessage (string strCommand, bool blnOnlyHeader) {_receiveFinish = false; if (SendCommand (strCommand)! Return null; try {string receivedContent = receivecontent (0, -1);

MimeParser.Message Msg = new mimeParser.Message (ref _ReceiveFinish, _basepath, _autodecodemstnef, receivedcontent, blnonlyhead);

WaitforResponse (_ReceiveFinish, WaitforResponseInterval);

Return Msg;} catch (exception e) {utility.loGerror ("fetchMessage ():" E.MESSAGE); Return null;}}

// Overload by Playyuer $ AT $ Microshaoft.com Public MimeParser.Message FetchMessage (int MessageID, String Strcommand, Bool BLNONLYHEADER) {_ReceiveFinish = false

String s = string.format (strcommand, messageid) .toupper (); if (! sendcommand (s)) Return NULL;

Try {string receivedContent = receivecontent (messageID, -1);

MimeParser.Message Msg = new mimeParser.Message (ref _ReceiveFinish, _basepath, _autodecodemstnef, receivedcontent, blnonlyhead);

WaitforResponse (_ReceiveFinish, WaitforResponseInterval);

Return Msg;} catch (exception e) {utility.loGerror ("fetchMessage ():" E.MESSAGE); Return null;}}

}

///

/// utility functions /// public class utility {/// /// Weather auto loggin is on or off /// private static bool m_blnlog = False; /// /// The file name in which the logging will be done /// private static string m_strlogfile = "openpop.log";

///

/// Turns file logging on and off.

Change property name /// /// Comming soon. public static bool log {get {return m_blnlog;} set {m_blnlog = value;}}

///

/// Log An Error To the log file /// /// The error text to log Internal static void logerror (String Strtext ) {// log = true; if (log) {fileInfo file = null; filestream fs = null; streamwriter sw = null; try {file = new fileinfo (m_strlogfile); sw = file.appendtext (); // fs = New filestream (m_strlogfile, filemode.openorcreate, fileaccess.write); // sw = new streamwriter (fs); sw.writeline (datetime.now); sw.writeline ("/ r / n" Sw.flush ();} finally {if (sw! = Null) {sw = null;} if (fs! = Null) {fs.close (); fs = NULL;}

}}}

}

}

// Exhaust Jmail's outerwear can not throw it to leave OpenPop.NET wear // "Package JMail 4.4 POP3 is .NET component (.dll assembly), implement" mail (attachment) arrive "" event "!" / * W3 Jmail v4.4 Professional Get Get Google! or see http://community.9cbs.net/expert/topicview.asp?id=3739405

W3 Jmail v4.4 Professional is a COM component, I use C # to package its POP3 COM class into a .NET component for collecting mail: implement the // Synchronous event public event messageeseventhandler messageReceReceiVed; // An email has been received To the local public event messageseageseventhandler messagereceive; // An email is arriving // can be used to charge each attachment for email processing public event attachmentseventhandler attachmentReceive; // An attachment of an email is arrived

// A abnormal event occurs public event message; public event attachmentseventhandler attachmentException;

Therefore, in the main adjustment program of the component, it can be different according to the results of the analysis email or attachment!

Will all code: 1. Copy to the new "Console Application" item of Microsoft Visual Studio .NET 2003 2. Then add the reference JMail 4.x library! Jmail's registration method, run the command line : Regsvr32 E: /JMAIL/JMAIL.DLL3.F5 run

Or you will be as follows: 1. Copy to any * .cs file saved in any * .cs file! (Such as: e: /temp/openmail.cs) 2. Generate a .NET program using the TLBIMP.EXE (Type Library Import) utility Set the command line: (in the MS VS.NET installation directory: e: /msvs.net/sdk/v1.1/bin/tlbimp.exe) TLBIMP.EXE E: /JMAIL/JMAIL.DLL / OUT: E : /temp/jmail.net.dll / name: Jmail generated jmail.net.dll with * .cs files in the same directory! 3. Execute the CSC command line compile * .cs compiled into EXE: (here is demonstration The test effect is compiled into an exe) csc.exe openmail.cs /r :jmail.net.dll compiled into a DLL, which can be added by other .NET programs: csc.exe / T: library openmail.cs / r: jmail. Net.dll

(Of course, you can also compile the code under Namespace Microshaoft.Openmail to DLL) * /

Namespace microshaoft.openmail {// using jmail; // useing system;

Public class pop3 {public delegate void MessageseVentHandler (MessageSstate OmessageSstate); Public Delegate Void AttachmentSeventHndler (AttachmentsState oatther);

// Asynchronous event Public Event MessageseesementHandler MessagesReceviceAnc; Public Event AttachmentSeventhandler AttachmentsRecEventageNC;

// Synchronous event Public Event MessagesementHandler MessageReceReceReceReceReceReceseventragereceRece; Public Event AttachmentSeventHandler AttachmentReceive;

// Exercise PUBLIC Event MessagesementHandler MessageException; Public Event AttachmentSeventHandler AttachmentException; Public Delegate Void DataEventHandler (int MessageID, int Data);

Public Event DataEventHandler DataArrival;

Private string _username; private string _password; private string _server; private int _port = 110;

Private static object _syncObject = new object ();

Public POP3 (String Username, String Password, String Server, int port) {this._username = username; this._parsword = password; this._server = server; THIS._PORT = port;

Public POP3 (String Username, String Password, String Server) {this._username = username; this._password = password; this._server = server;}

Public string username {get {return_username;} set {_username = value;}}

Public string password {get {return _password;} set {_password = value;}}

Public String Server {get {returb_server;} set {_server = value;}}

Public int port {get {return _port;} set {_port = value;}} // [mtathread] public void execute () {this.execute (false);} openpop.pop3.popclient POP3;

public void Execute {pop3 = new OpenPOP.POP3.POPClient (bool IsAsync) (); pop3.DataArrival = new OpenPOP.POP3.POPClient.DataEventHandler (pop3_DataArrival); try {//pop3.Timeout = 0; pop3.Connect ( this._Server, this._Port); pop3.Authenticate (this._UserName, this._Password); //jmail.MessagesClass jms = (jmail.MessagesClass) pop3.Messages; int I = pop3.GetMessageCount () ;; MessagesState omss = NULL; for (int i = 0; i

OASS.SAVETOFILE (s);}}

} Catch (System.Exception e) {if (this.AttachmentException = null!) {Oass.Exception = e; this.AttachmentException (oass); if (oass.ExceptionAction == Microshaoft.OpenMail.ExceptionActions.CancelAll) {break; } else if (oass.ExceptionAction == Microshaoft.OpenMail.ExceptionActions.Retry) {j--;} else if (oass.ExceptionAction == Microshaoft.OpenMail.ExceptionActions.Ignore) {// continue;} else if (oass. ExceptionAction == microshaoft.openmail.exceptionactions.throw) {throw e;}}}}}}}}}}}}}}}} {this.MESSAGERECEIVED (OMSS) ;}}}}} Catch (System.Exception e) {if (this.MessageException = null!) {Omss.Exception = e; this.MessageException (omss); if (omss.ExceptionAction == Microshaoft.OpenMail.ExceptionActions. CancelAll) {break;} else if (omss.ExceptionAction == Microshaoft.OpenMail.ExceptionActions.Retry) {i--;} else if (omss.ExceptionAction == Microshaoft.OpenMail.ExceptionActions.Ignore) {// continue;} Else if (oms.exception == microshaoft.openmail.exceptionactions.throw) {throw e;

}}}}}}} Catch (system.exception e) {throw e;} finally {pop3.disconnect (); pop3 = null;} //system.console.writeline("main end "); } // [MTAThread] private void MessageExecuteAsync (MessagesState oMessagesState) {int J = oMessagesState.jMessage.Attachments.Count; for (int j = 0; j

// [mtathread] private void attachmentexecuteasync (attachmentsstate oattementsstate) {//}

// [MTAThread] private void OnMessageCallBack (System.IAsyncResult iar) {MessagesState omss = (MessagesState) iar.AsyncState; if (! This.MessagesReceiveAsync = null) {if (omss.jMessage.Attachments.Count == 0) {this .MESSAGESRECEIVEASYNC (OMSS);}}}

// [MTAThread] private void OnAttachemnetCallBack (System.IAsyncResult iar) {AttachmentsState oass = (AttachmentsState) iar.AsyncState; if (this.AttachmentsReceiveAsync = null!) {This.AttachmentsReceiveAsync (oass);} if (! Oass.CancelCurrent) {try {oass.SaveToFile (oass.FileName);} catch (System.Exception e) {oass.Exception = e; if (AttachmentException = null!) {AttachmentException (oass); if (oass.ExceptionAction == Microshaoft.OpenMail .ExceptionActions.cancelall) {

} Else if (oass.ExceptionAction == Microshaoft.OpenMail.ExceptionActions.Retry) {this.OnAttachemnetCallBack ((System.IAsyncResult) oass);} else if (oass.ExceptionAction == Microshaoft.OpenMail.ExceptionActions.Ignore) {} else if (oass.ExceptionAction == Microshaoft.OpenMail.ExceptionActions.Throw) {throw e;}}}} if (! this.MessagesReceiveAsync = null) {if (oass.AttachmentsCount == 0) {this.MessagesReceiveAsync (oass.MessagesState }}}

Private void pop3_dataarrival (int messageid, int data) {if (dataarrival! = null) {dataArrival (MessageID, data);

}

public class MessagesState // Messages state {private static object _SyncObject = new object (); private int _MessageID; private OpenPOP.MIMEParser.Message _jMessage; // private jmail.MessagesClass _jMessages; private OpenPOP.POP3.POPClient _jPOP3; private string _FilePath; PRIVATE BOOL_CANCELCURRENT;

Private system.exception_exception; private exceptionAnch_exception;

Public int receivedLength {get {return _receivedLength;} set {_receivedlength = value;}}

Private int _ReceiveDLength;

Public ExceptionActions ExceptionAction {get {return_exceptionaction;} set {this._excectionAction = value;}}

Public system.exception exception {get {return _exception;} set {this._exception = value;}}

Public string filepath {get {return this._filepath;}}

INTERNAL VOID SETFILEPATH (String FilePath) {this._filepath = filepath;}

public bool CancelCurrent {get {return this._CancelCurrent;} set {this._CancelCurrent = value;}} public int MessagesCount // number of messages has not been processed {get {//lock(MessagesState._SyncObject) {return this._jPOP3.GetMessageCount () - this._messageid;}}}

Public openpop.mimeparser.Message Jimentage {get {returnid._jimentage;}}

Public int MessageId {get {returnid;}}

internal MessagesState (int MessageID, OpenPOP.MIMEParser.Message jMessage, OpenPOP.POP3.POPClient jPOP3) {this._MessageID = MessageID; this._jMessage = jMessage; //this._jMessages = jMessages; this._jPOP3 = jPOP3;}

Public void deleteSingleMessage () {Lock (message._syncObject) {this.deleteSingleMessage (this._messageid);}}

Public void deleteSingleMessage (INT messageID) {Lock (message._syncObject) {this._jpop3.deleteMessage (MessageID);}}

Public void deleteMedes () {lock (message._syncObject) {this._jpop3.deleteallMessages ();}}}

Public Enum ExceptionActions {Cancelall, Ignore, Retry, Throw}

public class AttachmentsState // Attachments state {private MessagesState _MessagesState; private int _AttachmentID; private string _FileName; private static object _SyncObject = new object (); private OpenPOP.MIMEParser.Attachment _jAttachment; private bool _CancelCurrent; private System.Exception _Exception; private ExceptionActions _Exception;

Public ExceptionActions ExceptionAction {get {return_exceptionaction;} set {this._excectionAction = value;}}

public System.Exception Exception {get {return _Exception;} set {this._Exception = value;}} public bool CancelCurrent {get {return this._CancelCurrent;} set {this._CancelCurrent = value;}}

Public openpop.mimeparser.attachment jattachment {get {return this._jattachment;}}

Public int attachmentscount // Number of mail attachments has not been processed {GET {//lock (atchmentsState._SyncObject) {return this._MessageSstate.jMessage.attachments.count - this._attachmentID - 1;}}}

Public string filename {get {returnşn_filename;} set {this._filename = value;}}

Public MessagesState MessageState {get {return this._MessageSstate;}}

Public int attachmentid {get {return this._attachmentId;}}

Public void savetofile (String filename) {// if (! this.cancelcurrent) {this._MessageSstate.jMessage.savettachment (_jattachment, filename);}}

internal AttachmentsState (int AttachmentID, MessagesState oMessagesState) {this._MessagesState = oMessagesState; this._AttachmentID = AttachmentID; this._jAttachment = (OpenPOP.MIMEParser.Attachment) oMessagesState.jMessage.Attachments [AttachmentID]; this._FileName = System.String. Format ( "[{0}] {1} [{2}] {3}...", oMessagesState.MessageID, oMessagesState.jMessage.Subject, attachmentID, oMessagesState.jMessage.GetAttachmentFileName (_jAttachment));}}} / / Write a test class below: Timed charge / / ======================================== ============================================================================================================================================================================================================= == // Console test procedure: namespace Microshaoft.OpenMail.ConsoleApplicationTest {using System; using Microshaoft.OpenMail; using POP = Microshaoft.OpenMail.POP3; class ConsoleApplicationTest {string POP3_Server = "mail.xxxx.com"; // System. Configuration.ConfigurationSettings.AppSettings [ "POP3_Server"]; string POP3_User = "userid"; // System.Configuration.ConfigurationSettings.AppSettings [ "POP3_User"]; string pOP3_Password = "password"; // System.Con Figureration.configurationSettings.AppSettings ["POP3_Password"];

Int interval = 20; // convert.Toint32 (System.configuration.configurations [TimerInterval "]);

POP POP1;

Bool isbusy = false;

static void Main () {ConsoleApplicationTest a = new ConsoleApplicationTest (); a.Pop1 = new POP (a.POP3_User, a.POP3_Password, a.POP3_Server); // synchronization event subscription a.Pop1.MessageReceived = new Microshaoft.OpenMail .POP3.MessagesEventHandler (a.Pop1_MessageReceived); a.Pop1.AttachmentReceive = new Microshaoft.OpenMail.POP3.AttachmentsEventHandler (a.Pop1_AttachmentReceive); a.Pop1.MessageReceive = new Microshaoft.OpenMail.POP3.MessagesEventHandler (a.Pop1_MessageReceive ); // subscribe Exception event a.Pop1.AttachmentException = new Microshaoft.OpenMail.POP3.AttachmentsEventHandler (a.Pop1_AttachmentException); a.Pop1.DataArrival = new Microshaoft.OpenMail.POP3.DataEventHandler (a.Pop1_DataArrival); at = new system.timers.timer (); atinterval = 1000 * a.interval; // Take a message Atelapsed = new system.timers.elapseDeventhandler (a.t_elapsed); a.t_elapsed (null, null every 30 seconds; a.t_elapsed); a.t_elapsed );

While (system.console.readline (). TOLOWER ()! = "exit") {system.console.writeline ("Press /" exit / "to exit this program!");}}

System.Timers.Timer T;

Private void t_elapsed (Object sender, system.timers.lapsendeventargs e) {this.run ();}

public void RefreshSettings () {System.Xml.XmlDocument xd = new System.Xml.XmlDocument (); xd.Load (System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); POP3_Server = xd.SelectSingleNode ( "/ configuration / appSettings / add [@key = / "POP3_Server /"] "[value"]) Attributes. "value;. //System.Configuration.ConfigurationSettings.AppSettings["POP3_Server"]; POP3_User = xd.SelectSingleNode ( "/ configuration / appSettings / add [@key = / "POP3_User /"] "[value"]) Attributes. "value;. //System.Configuration.ConfigurationSettings.AppSettings["POP3_User"]; pOP3_Password = xd.SelectSingleNode ( "/ configuration / appSettings / add ".) Attributes [@key = /" pOP3_Password / "] [" value "] value;. //System.Configuration.ConfigurationSettings.AppSettings["POP3_User"];//System.Configuration.ConfigurationSettings.AppSettings["POP3_Password" ]; Interval = Convert.Toint32 ("/ configuration / appsettinglEnode (" / configuration / appsettings / add [@key = / "timerinterval /"] "). Attributes [" value "]. Value); t.interval = interval * 1000; this.pop1.username = po P3_user; this.pop1.password = pop3_password; this.pop1.server = pop3_server;} private void dowait () {wait (ref isbusy); // is a true function of the commissioned call}

Private void run () {if (! isbusy) {system.console.writeline ("/ nbusy {0}", system.datetime.now.tolocaltime (). TouniversalTime (); this.t.enabled = false; this .Isbusy = true; //this.pop1.execute (true); // Perform // refreshSettings (); try {this.pop1.execute (); // Synchronous execution} catch (system.exception ex) {System.Exception ex) {System.Exception EX .Console.writeline (ex.Message);} finally {this.isbusy = false; t.enabled = true; // refreshSettings (); this.Idle ();}}} private void idle () {system.console. WriteLine ("/ Nidle {0}", System.Datetime.now.tolocaltime (). TouniversalTime ()); System.Console.writeline ("The Program Will Receive Mails Next Time, After" T. Interval.Tostring () "MS"); System.Console.writeline ("Press /" exit / "to exit this program!"); new system.threading.thread (new system.threading.threadstart ()). start (); / / Monitor thread: Display scrolling counter}

PRIVATE VOID POP1_MESSAGESRECEIVEASYNC (MessageSstate OmessageSstate) {}

private void Pop1_MessageReceived (MessagesState oMessagesState) {System.Console.WriteLine ( "/ nMessage:.! [{0}] {1} of {2} Messages have been recieved {3}", oMessagesState.MessageID, oMessagesState.jMessage.Subject , 0, OmessageSstate.Messagescount);

// You can delete if an email is deleted every email, {//00ssagesstate.deleteSingleMessage (ExesState.MESSAGEID);}}

Private Void Wait (Ref Bool Flag) // Flag can change {INT i = 0 in other threads; string bs = ""; string s = ""; while (! flag) {s = system.datetime.now.tostring ( ); System.console.write (BS "/ b / b" i "second," s); system.threading.thread.sleep (1000); // 1 second bs = new string ('/ b', DIGITS (I) S.LENGTH 1); // 19 is the date time string length, 1 is ","} //system.console.writeLine ();} private void pop1_attachmentReceive (AttachmentsState oAttachmentsState) {oAttachmentsState.CancelCurrent = true; //System.Console.WriteLine(oAttachmentsState.FileName); if (oAttachmentsState.MessagesState.CancelCurrent) {string S = @! "e: / temp /" oAttachmentsState.FileName; oAttachmentsState. Savetofile (s);}}

Private void pop1_MessageReceive (MessageSstate OmessageState) {//00ssagesstate.cancelcurrent = true; if (OMESSAGESSTATE.JMESSAGE.SUBJECT! = NULL) {

}

private void Pop1_AttachmentException (Microshaoft.OpenMail.AttachmentsState oAttachmentsState) {System.Console.WriteLine ( "Execute Exception: {0}", oAttachmentsState.Exception.Message); oAttachmentsState.FileName = "e: // temp // copy of" oAttachmentsState.jAttachment.DefaultFileName; oAttachmentsState.ExceptionAction = Microshaoft.OpenMail.ExceptionActions.Retry; // a document name after reprocessing oAttachmentsState.ExceptionAction = Microshaoft.OpenMail.ExceptionActions.Ignore; // process a next attachment //oAttachmentsState.ExceptionAction = Microshaoft.openmail.exceptionactions.throw;}

String BS = ""; // Used to record the last bit number private void pop1_dataarrival (int messageid, int data) {if (data == 0) {system.console.writeLine (); system.console.write (" Message: [{0}] data has been received: ", MessageID); BS =" ";} if (data> 0) {system.console.write (BS " / B / B " DATA " line "); Bs = new string ('/ b', digits (data));} INT DIGITS (INT N) // Number of placeholders {n = system.math.abs (n); n = n / 10 ; Int i = 1; while (n> 0) {n = N / 10; i ;} return i;}}}

/ / =========================================================================================================================================================================================== ======================================================= // Windows test procedure:

Namespace microshaoft.openmail.windowsapplicationtest {using system; using system.windows.form;

///

/// Form1 summary description. /// public class Form1: System.Windows.Forms.Form {private System.Windows.Forms.Button button1; private System.Windows.Forms.Timer timer1; private System.ComponentModel.IContainer components;

Public Form1 () {// // Windows Form Designer Support for // InitializeComponent ();

// // Todo: Add any constructor code after INITIALIZEComponent call //}

///

/// Clean all the resources being used. /// Protected Override Void Dispose (Bool Disposing) {if (disponents! = null) {Components.dispose ();}} Base.Dispose (DISPOSION);} #Region Windows Form Code generated by the designer

///

/// Designer supports the required method - do not use the code editor to modify the // / this method. /// private void InitializeComponent () {this.components = new System.ComponentModel.Container (); this.button1 = new System.Windows.Forms.Button (); this.timer1 = new System.Windows. Forms.timer (this.components); this.suspendlayout (); // // button1 // this.button1.location = new system.drawing.point (24, 24); this.button1.name = "button1"; This.Button1.Size = new system.drawing.size (80, 40); this.button1.tabindex = 0; this.button1.text = "button1"; this.button1.click = new System.EventHandler (this. Button1_click; // // Timer1 // this.timer1.tick = new system.EventHandler (this.timer1_tick); // // Form1 // this.autoscalebasesize = new system.drawing.size (6, 14); This.ClientSize = new system.drawing.size (292, 273); this.controls.add (this.button1); this.name = "form1"; this.text = "form1"; this.ResumeLayout (false);

}

#ndregion

///

/// The primary entry point of the application. /// [stathread] public static void main0 () // main () // To change back to main () {Application.run (New Form1 ());}

Private microshaoft.openmail.pop3 x;

private void button1_Click (object sender, System.EventArgs e) {timer1.Interval = 1000 * 120; // receive messages once every 120 seconds new System.Threading.Thread (new System.Threading.ThreadStart (this.ThreadProc)) Start. (); //This.ThreadProc ();

private void ThreadProc () {button1.Enabled = false; x = new Microshaoft.OpenMail.POP3 ( "UserName", "Password", "mail.xxx.com"); x.MessageReceive = new Microshaoft.OpenMail.POP3. MessagesEventHandler (x_MessageReceive); x.MessageReceived = new Microshaoft.OpenMail.POP3.MessagesEventHandler (x_MessageReceived); x.AttachmentReceive = new Microshaoft.OpenMail.POP3.AttachmentsEventHandler (x_AttachmentReceive); x.AttachmentException = new Microshaoft.OpenMail.POP3 .AttachmentsEventHandler (x_AttachmentException); timer1.Interval = 1000 * 120; // receive mail once every 120 seconds timer1.Enabled = false; x.Execute (); button1.Enabled = true;} private void x_MessageReceive (Microshaoft.OpenMail.MessagesState OmessageSstate) {//system.windows.Forms.MessageBox.show (OmessageSstate.MessageId.Tostring ()); System.Console.writeline ("{0}," {1} ", OMESSAGESSTATE.MESSAGEID.TOSTRING (), OMESSAGESSTATE.JMESSAGE.SUBJECT);

//System.console.writeline (BassageSstate.jimentage.body); //system.console.writeline(OMessageSstate.jimentage.text);

}

Private void Timer1_Tick (Object Sender, System.EventArgs E) {//x.execute (); new system.threading.thread (new system.threading.threadstart (this.threadproc)). Start ();}

private void x_MessageReceived (Microshaoft.OpenMail.MessagesState oMessagesState) {if (oMessagesState.MessagesCount == 0) {//System.Windows.Forms.MessageBox.Show("game over ");} else {System.Console.WriteLine (oMessagesState .MessageId.toString ());}}

private void x_AttachmentReceive (Microshaoft.OpenMail.AttachmentsState oAttachmentsState) {oAttachmentsState.FileName = "e: // temp //" oAttachmentsState.FileName; oAttachmentsState.SaveToFile (oAttachmentsState.FileName); if (oAttachmentsState.Exception = null!) {/ / throw oAttachmentsState.Exception;} oAttachmentsState.CancelCurrent = true; // Save processing is not currently attachments if (oAttachmentsState.AttachmentsCount == 0) {//System.Windows.Forms.MessageBox.Show(oAttachmentsState.MessagesState.jMessage.Attachments. Count.toString ());} else {system.console.writeline (oattachmentsstate.attachmentid.tostring ());}}

private void x_AttachmentException (Microshaoft.OpenMail.AttachmentsState oAttachmentsState) {System.Console.WriteLine ( "Execute Exception: {0}", oAttachmentsState.Exception.Message); oAttachmentsState.FileName = "e: // temp // copy of" oAttachmentsState.jAttachment.DefaultFileName; //oAttachmentsState.ExceptionAction = Microshaoft.OpenMail.ExceptionActions.Retry; // a document name after reprocessing oAttachmentsState.ExceptionAction = Microshaoft.OpenMail.ExceptionActions.Ignore; // process a next attachment // oAttachmentsState .Exception.openmail.exceptionactions.THROW;}}}

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

New Post(0)