/ * 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;
///
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
///
///
///
}
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
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;}
///
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 (); ///
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;}} ///
///
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;} ///
///
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}
///
///
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 /// 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 (); /// Return ConvertHexContent (HexString, Encoding.default, 0); } /// #ndregion #Region Properties /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// #ndregion {_ _b (); _keywords = null; _keywords = null;........................... .. _MessageBody = null; _CustomHeaders.clear (); _CustomHeaders = null; /// /// /// /// 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; /// /// 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; /// /// strBody = strBody.Replace (att.ContentFileName, hsbFiles [att.ContentFileName] .ToString ());}}} catch (Exception e) {Utility.LogError ( "TranslateHTMLPictureFiles ():" e.Message);} return strBody } /// /// // 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); /// IF ("//")) {strpath = "//";} for (int i = 0; i /// /// 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 ;}} /// /// 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 } /// //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); /// 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); /// 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;}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}} summary> 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 ");} /// 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";} } } /// BYTE [] NEWARRAY = New byte [bufferPosition]; array.copy (buffer, newarray); return newaRray;} /// 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) } /// } /// Private string _filename = ""; private long _fileLength = 0; private string _subject = ""; private bote [] _filecontent = null; #ndregion #Region Properties /// /// /// #ndregion Public tnefattachment () {} ~ Tnefattachment () {_filecontent = null;}} /// 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);} /// 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;}} /// /// 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 IF (i <4) PrintResult ("{0}", v); ELSE IF (i == 4) PrintResult ("...");} PrintResult ("/ n"); Break; Case_String: streamreadbytes BUF, LEN); 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 StreamReadBytes (buf, chunk); Array.copy (buf, 0, _attachment.filecontent, i, chun); i = chunk;} Geti16 (); / * checksum * / Break; DEFAULT: DECODE_ATRIBUTE (D); Break;}} /// /// While (ideattachments.movenext ()) {blnret = saveattachment (tnefattachment) deattachments.value);} return blnret;} /// /// 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 ()} /// /// /// 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; //} // /// Strret = quotetext (strret, " "); strret = quottext (strret, "-"); strret = quotetext (strret, "gmt"); strret = quottext (strret, "cst"); return strret.trim () } /// Return Strret; /// /// /// 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; /// 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;} * /} /// /// /// /// /// 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 = @ "/ = /? (? 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 /// 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; /// 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; /// /// /// /// /// /// /// /// 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; } } /// /// /// /// /// /// /// 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;}} /// /// /// /// /// /// 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);}} /// /// /// /// /// /// 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 ();}} /// /// /// /// 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); /// 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; /// /// /// /// /// /// /// /// // Modify by Playyuer $ AT $ microshaoft.com mimeParser.MESSAGE MSG = FetchMessage (IntMessagenumber, "TOP {0} 0", TRUE); OnmessageTransferfinished (Eventargs.empty); Return msg; /// /// /// // 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);} /// 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 (); } /// // modify by Playyuer $ AT $ microshaoft.com mimeParser.Mestage MSG = FetchMessage (INTNUMBER, "Retr {0}", BLNONLYHEADER); OnmessageTransferfinished (Eventargs.empty); Return msg; /// 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;}} } /// /// /// }}} } } // 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; /// Public Form1 () {// // Windows Form Designer Support for // InitializeComponent (); // // Todo: Add any constructor code after INITIALIZEComponent call //} /// /// } #ndregion /// 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;}}} Change property name h1> font> /// summary> ///