Beispiel #1
0
        private void Store(string cmdTag,string argsText,bool uidStore)
        {
            /* Rfc 3501 6.4.6 STORE Command

                Arguments:  message set
                            message data item name
                            value for message data item

                Responses:  untagged responses: FETCH

                Result:     OK - store completed
                            NO - store error: can't store that data
                            BAD - command unknown or arguments invalid

                The STORE command alters data associated with a message in the
                mailbox.  Normally, STORE will return the updated value of the
                data with an untagged FETCH response.  A suffix of ".SILENT" in
                the data item name prevents the untagged FETCH, and the server
                SHOULD assume that the client has determined the updated value
                itself or does not care about the updated value.

                Note: regardless of whether or not the ".SILENT" suffix was
                    used, the server SHOULD send an untagged FETCH response if a
                    change to a message's flags from an external source is
                    observed.  The intent is that the status of the flags is
                    determinate without a race condition.

                The currently defined data items that can be stored are:

                FLAGS <flag list>
                    Replace the flags for the message (other than \Recent) with the
                    argument.  The new value of the flags is returned as if a FETCH
                    of those flags was done.

                FLAGS.SILENT <flag list>
                    Equivalent to FLAGS, but without returning a new value.

                +FLAGS <flag list>
                    Add the argument to the flags for the message.  The new value
                    of the flags is returned as if a FETCH of those flags was done.

                +FLAGS.SILENT <flag list>
                    Equivalent to +FLAGS, but without returning a new value.

                -FLAGS <flag list>
                    Remove the argument from the flags for the message.  The new
                    value of the flags is returned as if a FETCH of those flags was
                    done.

                -FLAGS.SILENT <flag list>
                    Equivalent to -FLAGS, but without returning a new value.

                Example:    C: A003 STORE 2:4 +FLAGS (\Deleted)
                            S: * 2 FETCH FLAGS (\Deleted \Seen)
                            S: * 3 FETCH FLAGS (\Deleted)
                            S: * 4 FETCH FLAGS (\Deleted \Flagged \Seen)
                            S: A003 OK STORE completed

            */
            if(!this.Authenticated){
                this.Socket.WriteLine(cmdTag + " NO Authenticate first !");
                return;
            }
            if(m_SelectedMailbox.Length == 0){
                this.Socket.WriteLine(cmdTag + " NO Select mailbox first !");
                return;
            }
            if(m_pSelectedFolder.ReadOnly){
                this.Socket.WriteLine(cmdTag + " NO Mailbox is read-only");
                return;
            }

            // Store start time
            long startTime = DateTime.Now.Ticks;

            string[] args = ParseParams(argsText);
            if(args.Length != 3){
                this.Socket.WriteLine(cmdTag + " BAD STORE invalid arguments. Syntax: {<command-tag> STORE <sequnce-set> <data-item> (<message-flags>)}");
                return;
            }

            IMAP_SequenceSet sequenceSet = new IMAP_SequenceSet();
            // Just try if it can be parsed as sequence-set
            try{
                if(uidStore){
                    if(m_pSelectedFolder.Messages.Count > 0){
                        sequenceSet.Parse(args[0],m_pSelectedFolder.Messages[m_pSelectedFolder.Messages.Count - 1].UID);
                    }
                }
                else{
                    sequenceSet.Parse(args[0],m_pSelectedFolder.Messages.Count);
                }
            }
            // This isn't vaild sequnce-set value
            catch{
                this.Socket.WriteLine(cmdTag + "BAD Invalid <sequnce-set> value '" + args[0] + "' Syntax: {<command-tag> STORE <sequnce-set> <data-item> (<message-flags>)}!");
                return;
            }

            //--- Parse Flags behaviour ---------------//
            string flagsAction = "";
            bool   silent      = false;
            string flagsType = args[1].ToUpper();
            switch(flagsType)
            {
                case "FLAGS":
                    flagsAction = "REPLACE";
                    break;

                case "FLAGS.SILENT":
                    flagsAction = "REPLACE";
                    silent = true;
                    break;

                case "+FLAGS":
                    flagsAction = "ADD";
                    break;

                case "+FLAGS.SILENT":
                    flagsAction = "ADD";
                    silent = true;
                    break;

                case "-FLAGS":
                    flagsAction = "REMOVE";
                    break;

                case "-FLAGS.SILENT":
                    flagsAction = "REMOVE";
                    silent = true;
                    break;

                default:
                    this.Socket.WriteLine(cmdTag + " BAD arguments invalid");
                    return;
            }
            //-------------------------------------------//

            //--- Parse flags, see if valid ----------------
            string flags = args[2].ToUpper();
            if(flags.Replace("\\ANSWERED","").Replace("\\FLAGGED","").Replace("\\DELETED","").Replace("\\SEEN","").Replace("\\DRAFT","").Trim().Length > 0){
                this.Socket.WriteLine(cmdTag + " BAD arguments invalid");
                return;
            }

            IMAP_MessageFlags mFlags = IMAP_Utils.ParseMessageFlags(flags);

            // Call OnStoreMessageFlags for each message in sequence set
            // Calulate new flags(using old message flags + new flags) for message
            // and request to store all flags to message, don't specify if add, remove or replace falgs.

            for(int i=0;i<m_pSelectedFolder.Messages.Count;i++){
                IMAP_Message msg = m_pSelectedFolder.Messages[i];

                // For UID STORE we must compare UIDs and for normal STORE message numbers.
                bool sequenceSetContains = false;
                if(uidStore){
                    sequenceSetContains = sequenceSet.Contains(msg.UID);
                }
                else{
                    sequenceSetContains = sequenceSet.Contains(i + 1);
                }

                if(sequenceSetContains){
                    // Calculate new flags and set to msg
                    switch(flagsAction)
                    {
                        case "REPLACE":
                            msg.SetFlags(mFlags);
                            break;

                        case "ADD":
                            msg.SetFlags(msg.Flags | mFlags);
                            break;

                        case "REMOVE":
                            msg.SetFlags(msg.Flags & ~mFlags);
                            break;
                    }

                    // ToDo: see if flags changed, if not don't call OnStoreMessageFlags

                    string errorText = m_pServer.OnStoreMessageFlags(this,msg);
                    if(errorText == null){
                        if(!silent){ // Silent doesn't reply untagged lines
                            if(!uidStore){
                                this.Socket.WriteLine("* " + (i + 1) + " FETCH FLAGS (" + msg.FlagsString + ")");
                            }
                            // Called from UID command, need to add UID response
                            else{
                                this.Socket.WriteLine("* " + (i + 1) + " FETCH (FLAGS (" + msg.FlagsString + ") UID " + msg.UID + "))");
                            }
                        }
                    }
                    else{
                        this.Socket.WriteLine(cmdTag + " NO " + errorText);
                        return;
                    }
                }
            }

            this.Socket.WriteLine(cmdTag + " OK STORE completed in " + ((DateTime.Now.Ticks - startTime) / (decimal)10000000).ToString("f2") + " seconds");
        }
Beispiel #2
0
        private void Copy(string cmdTag,string argsText,bool uidCopy)
        {
            /* RFC 3501 6.4.7 COPY Command

                Arguments:  message set
                            mailbox name

                Responses:  no specific responses for this command

                Result:     OK - copy completed
                            NO - copy error: can't copy those messages or to that
                                    name
                            BAD - command unknown or arguments invalid

                The COPY command copies the specified message(s) to the end of the
                specified destination mailbox.  The flags and internal date of the
                message(s) SHOULD be preserved in the copy.

                If the destination mailbox does not exist, a server SHOULD return
                an error.  It SHOULD NOT automatically create the mailbox.  Unless
                it is certain that the destination mailbox can not be created, the
                server MUST send the response code "[TRYCREATE]" as the prefix of
                the text of the tagged NO response.  This gives a hint to the
                client that it can attempt a CREATE command and retry the COPY if

                If the COPY command is unsuccessful for any reason, server
                implementations MUST restore the destination mailbox to its state
                before the COPY attempt.

                Example:    C: A003 COPY 2:4 MEETING
                            S: A003 OK COPY completed

            */
            if(!this.Authenticated){
                this.Socket.WriteLine(cmdTag + " NO Authenticate first !");
                return;
            }
            if(m_SelectedMailbox.Length == 0){
                this.Socket.WriteLine(cmdTag + " NO Select mailbox first !");
                return;
            }

            string[] args = ParseParams(argsText);
            if(args.Length != 2){
                this.Socket.WriteLine(cmdTag + " BAD Invalid arguments");
                return;
            }

            IMAP_SequenceSet sequenceSet = new IMAP_SequenceSet();
            // Just try if it can be parsed as sequence-set
            try{
                if(uidCopy){
                    if(m_pSelectedFolder.Messages.Count > 0){
                        sequenceSet.Parse(args[0],m_pSelectedFolder.Messages[m_pSelectedFolder.Messages.Count - 1].UID);
                    }
                }
                else{
                    sequenceSet.Parse(args[0],m_pSelectedFolder.Messages.Count);
                }
            }
            // This isn't vaild sequnce-set value
            catch{
                this.Socket.WriteLine(cmdTag + "BAD Invalid <sequnce-set> value '" + args[0] + "' Syntax: {<command-tag> COPY <sequnce-set> \"<mailbox-name>\"}!");
                return;
            }

            string errorText = "";
            for(int i=0;i<m_pSelectedFolder.Messages.Count;i++){
                IMAP_Message msg = m_pSelectedFolder.Messages[i];

                // For UID COPY we must compare UIDs and for normal COPY message numbers.
                bool sequenceSetContains = false;
                if(uidCopy){
                    sequenceSetContains = sequenceSet.Contains(msg.UID);
                }
                else{
                    sequenceSetContains = sequenceSet.Contains(i + 1);
                }

                if(sequenceSetContains){
                    errorText = m_pServer.OnCopyMessage(this,msg,Core.Decode_IMAP_UTF7_String(args[1]));
                    if(errorText != null){
                        break; // Errors return error text, don't try to copy other messages
                    }
                }
            }

            if(errorText == null){
                this.Socket.WriteLine(cmdTag + " OK COPY completed");
            }
            else{
                this.Socket.WriteLine(cmdTag + " NO " + errorText);
            }
        }
Beispiel #3
0
        private void Fetch(string cmdTag,string argsText,bool uidFetch)
        {
            /* Rfc 3501 6.4.5 FETCH Command

                Arguments:  message set
                            message data item names

                Responses:  untagged responses: FETCH

                Result:     OK - fetch completed
                            NO - fetch error: can't fetch that data
                            BAD - command unknown or arguments invalid

                The FETCH command retrieves data associated with a message in the
                mailbox.  The data items to be fetched can be either a single atom
                or a parenthesized list.

            Most data items, identified in the formal syntax under the
            msg-att-static rule, are static and MUST NOT change for any
            particular message.  Other data items, identified in the formal
            syntax under the msg-att-dynamic rule, MAY change, either as a
            result of a STORE command or due to external events.

                For example, if a client receives an ENVELOPE for a
                message when it already knows the envelope, it can
                safely ignore the newly transmitted envelope.

            There are three macros which specify commonly-used sets of data
            items, and can be used instead of data items.  A macro must be
            used by itself, and not in conjunction with other macros or data
            items.

            ALL
                Macro equivalent to: (FLAGS INTERNALDATE RFC822.SIZE ENVELOPE)

            FAST
                Macro equivalent to: (FLAGS INTERNALDATE RFC822.SIZE)

            FULL
                Macro equivalent to: (FLAGS INTERNALDATE RFC822.SIZE ENVELOPE
                BODY)

            The currently defined data items that can be fetched are:

            BODY
                Non-extensible form of BODYSTRUCTURE.

            BODY[<section>]<<partial>>
                The text of a particular body section.  The section
                specification is a set of zero or more part specifiers
                delimited by periods.  A part specifier is either a part number
                or one of the following: HEADER, HEADER.FIELDS,
                HEADER.FIELDS.NOT, MIME, and TEXT.  An empty section
                specification refers to the entire message, including the
                header.

                Every message has at least one part number.  Non-[MIME-IMB]
                messages, and non-multipart [MIME-IMB] messages with no
                encapsulated message, only have a part 1.

                Multipart messages are assigned consecutive part numbers, as
                they occur in the message.  If a particular part is of type
                message or multipart, its parts MUST be indicated by a period
                followed by the part number within that nested multipart part.

                A part of type MESSAGE/RFC822 also has nested part numbers,
                referring to parts of the MESSAGE part's body.

                The HEADER, HEADER.FIELDS, HEADER.FIELDS.NOT, and TEXT part
                specifiers can be the sole part specifier or can be prefixed by
                one or more numeric part specifiers, provided that the numeric
                part specifier refers to a part of type MESSAGE/RFC822.  The
                MIME part specifier MUST be prefixed by one or more numeric
                part specifiers.

                The HEADER, HEADER.FIELDS, and HEADER.FIELDS.NOT part
                specifiers refer to the [RFC-2822] header of the message or of
                an encapsulated [MIME-IMT] MESSAGE/RFC822 message.
                HEADER.FIELDS and HEADER.FIELDS.NOT are followed by a list of
                field-name (as defined in [RFC-2822]) names, and return a
                subset of the header.  The subset returned by HEADER.FIELDS
                contains only those header fields with a field-name that
                matches one of the names in the list; similarly, the subset
                returned by HEADER.FIELDS.NOT contains only the header fields
                with a non-matching field-name.  The field-matching is
                case-insensitive but otherwise exact.  Subsetting does not
                exclude the [RFC-2822] delimiting blank line between the header
                and the body; the blank line is included in all header fetches,
                except in the case of a message which has no body and no blank
                line.

                The MIME part specifier refers to the [MIME-IMB] header for
                this part.

                The TEXT part specifier refers to the text body of the message,
                omitting the [RFC-2822] header.

                    Here is an example of a complex message with some of its
                    part specifiers:

                    HEADER     ([RFC-2822] header of the message)
                    TEXT       ([RFC-2822] text body of the message) MULTIPART/MIXED
                    1          TEXT/PLAIN
                    2          APPLICATION/OCTET-STREAM
                    3          MESSAGE/RFC822
                    3.HEADER   ([RFC-2822] header of the message)
                    3.TEXT     ([RFC-2822] text body of the message) MULTIPART/MIXED
                    3.1        TEXT/PLAIN
                    3.2        APPLICATION/OCTET-STREAM
                    4          MULTIPART/MIXED
                    4.1        IMAGE/GIF
                    4.1.MIME   ([MIME-IMB] header for the IMAGE/GIF)
                    4.2        MESSAGE/RFC822
                    4.2.HEADER ([RFC-2822] header of the message)
                    4.2.TEXT   ([RFC-2822] text body of the message) MULTIPART/MIXED
                    4.2.1      TEXT/PLAIN
                    4.2.2      MULTIPART/ALTERNATIVE
                    4.2.2.1    TEXT/PLAIN
                    4.2.2.2    TEXT/RICHTEXT

                It is possible to fetch a substring of the designated text.
                This is done by appending an open angle bracket ("<"), the
                octet position of the first desired octet, a period, the
                maximum number of octets desired, and a close angle bracket
                (">") to the part specifier.  If the starting octet is beyond
                the end of the text, an empty string is returned.

                Any partial fetch that attempts to read beyond the end of the
                text is truncated as appropriate.  A partial fetch that starts
                at octet 0 is returned as a partial fetch, even if this
                truncation happened.

                    Note: This means that BODY[]<0.2048> of a 1500-octet message
                    will return BODY[]<0> with a literal of size 1500, not
                    BODY[].

                    Note: A substring fetch of a HEADER.FIELDS or
                    HEADER.FIELDS.NOT part specifier is calculated after
                    subsetting the header.

                The \Seen flag is implicitly set; if this causes the flags to
                change, they SHOULD be included as part of the FETCH responses.

            BODY.PEEK[<section>]<<partial>>
                An alternate form of BODY[<section>] that does not implicitly
                set the \Seen flag.

            BODYSTRUCTURE
                The [MIME-IMB] body structure of the message.  This is computed
                by the server by parsing the [MIME-IMB] header fields in the
                [RFC-2822] header and [MIME-IMB] headers.

            ENVELOPE
                The envelope structure of the message.  This is computed by the
                server by parsing the [RFC-2822] header into the component
                parts, defaulting various fields as necessary.

            FLAGS
                The flags that are set for this message.

            INTERNALDATE
                The internal date of the message.

            RFC822
                Functionally equivalent to BODY[], differing in the syntax of
                the resulting untagged FETCH data (RFC822 is returned).

            RFC822.HEADER
                Functionally equivalent to BODY.PEEK[HEADER], differing in the
                syntax of the resulting untagged FETCH data (RFC822.HEADER is
                returned).

            RFC822.SIZE
                The [RFC-2822] size of the message.

            RFC822.TEXT
                Functionally equivalent to BODY[TEXT], differing in the syntax
                of the resulting untagged FETCH data (RFC822.TEXT is returned).

            UID
                The unique identifier for the message.

            Example:    C: A654 FETCH 2:4 (FLAGS BODY[HEADER.FIELDS (DATE FROM)])
                        S: * 2 FETCH ....
                        S: * 3 FETCH ....
                        S: * 4 FETCH ....
                        S: A654 OK FETCH completed

            */
            if(!this.Authenticated){
                this.Socket.WriteLine(cmdTag + " NO Authenticate first !");
                return;
            }
            if(m_SelectedMailbox.Length == 0){
                this.Socket.WriteLine(cmdTag + " NO Select mailbox first !");
                return;
            }

            // Store start time
            long startTime = DateTime.Now.Ticks;

            IMAP_MessageItems_enum messageItems = IMAP_MessageItems_enum.None;

            #region Parse parameters

            string[] args = ParseParams(argsText);
            if(args.Length != 2){
                this.Socket.WriteLine(cmdTag + " BAD Invalid arguments");
                return;
            }

            IMAP_SequenceSet sequenceSet = new IMAP_SequenceSet();
            // Just try if it can be parsed as sequence-set
            try{
                if(uidFetch){
                    if(m_pSelectedFolder.Messages.Count > 0){
                        sequenceSet.Parse(args[0],m_pSelectedFolder.Messages[m_pSelectedFolder.Messages.Count - 1].UID);
                    }
                }
                else{
                    sequenceSet.Parse(args[0],m_pSelectedFolder.Messages.Count);
                }
            }
            // This isn't valid sequnce-set value
            catch{
                this.Socket.WriteLine(cmdTag + " BAD Invalid <sequnce-set> value '" + args[0] + "' Syntax: {<command-tag> FETCH <sequnce-set> (<fetch-keys>)}!");
                return;
            }

            // Replace macros
            string fetchItems = args[1].ToUpper();
                   fetchItems = fetchItems.Replace("ALL" ,"FLAGS INTERNALDATE RFC822.SIZE ENVELOPE");
                   fetchItems = fetchItems.Replace("FAST","FLAGS INTERNALDATE RFC822.SIZE");
                   fetchItems = fetchItems.Replace("FULL","FLAGS INTERNALDATE RFC822.SIZE ENVELOPE BODY");

            // If UID FETCH and no UID, we must implicity add it, it's required
            if(uidFetch && fetchItems.ToUpper().IndexOf("UID") == -1){
                fetchItems += " UID";
            }

            // Start parm parsing from left to end in while loop while params parsed or bad param found
            ArrayList fetchFlags = new ArrayList();
            StringReader argsReader = new StringReader(fetchItems.Trim());
            while(argsReader.Available > 0){
                argsReader.ReadToFirstChar();

                #region BODYSTRUCTURE

                // BODYSTRUCTURE
                if(argsReader.StartsWith("BODYSTRUCTURE")){
                    argsReader.ReadSpecifiedLength("BODYSTRUCTURE".Length);

                    fetchFlags.Add(new object[]{"BODYSTRUCTURE"});
                    messageItems |= IMAP_MessageItems_enum.BodyStructure;
                }

                #endregion

                #region BODY, BODY[<section>]<<partial>>, BODY.PEEK[<section>]<<partial>>

                // BODY, BODY[<section>]<<partial>>, BODY.PEEK[<section>]<<partial>>
                else if(argsReader.StartsWith("BODY")){
                    // Remove BODY
                    argsReader.ReadSpecifiedLength("BODY".Length);

                    bool peek = false;
                    // BODY.PEEK
                    if(argsReader.StartsWith(".PEEK")){
                        // Remove .PEEK
                        argsReader.ReadSpecifiedLength(".PEEK".Length);

                        peek = true;
                    }

                    // [<section>]<<partial>>
                    if(argsReader.StartsWith("[")){
                        // Read value between []
                        string section = "";
                        try{
                            section = argsReader.ReadParenthesized();
                        }
                        catch{
                            this.Socket.WriteLine(cmdTag + " BAD Invalid BODY[], closing ] parenthesize is missing !");
                            return;
                        }

                        string originalSectionValue = section;
                        string mimePartsSpecifier = "";
                        string sectionType = "";
                        string sectionArgs = "";
                        /* Validate <section>
                             Section can be:
                                ""                                                    - entire message
                                [MimePartsSepcifier.]HEADER                           - message header
                                [MimePartsSepcifier.]HEADER.FIELDS (headerFields)     - message header fields
                                [MimePartsSepcifier.]HEADER.FIELDS.NOT (headerFields) - message header fields except requested
                                [MimePartsSepcifier.]TEXT                             - message text
                                [MimePartsSepcifier.]MIME                             - same as header, different response
                        */
                        if(section.Length > 0){
                            string[] section_args = section.Split(new char[]{' '},2);
                            section = section_args[0];
                            if(section_args.Length == 2){
                                sectionArgs = section_args[1];
                            }

                            if(section.EndsWith("HEADER")){
                                // Remove HEADER from end
                                section = section.Substring(0,section.Length - "HEADER".Length);

                                sectionType = "HEADER";
                                messageItems |= IMAP_MessageItems_enum.Header;
                            }
                            else if(section.EndsWith("HEADER.FIELDS")){
                                // Remove HEADER.FIELDS from end
                                section = section.Substring(0,section.Length - "HEADER.FIELDS".Length);

                                sectionType = "HEADER.FIELDS";
                                messageItems |= IMAP_MessageItems_enum.Header;
                            }
                            else if(section.EndsWith("HEADER.FIELDS.NOT")){
                                // Remove HEADER.FIELDS.NOT from end
                                section = section.Substring(0,section.Length - "HEADER.FIELDS.NOT".Length);

                                sectionType = "HEADER.FIELDS.NOT";
                                messageItems |= IMAP_MessageItems_enum.Header;
                            }
                            else if(section.EndsWith("TEXT")){
                                // Remove TEXT from end
                                section = section.Substring(0,section.Length - "TEXT".Length);

                                sectionType = "TEXT";
                                messageItems |= IMAP_MessageItems_enum.Message;
                            }
                            else if(section.EndsWith("MIME")){
                                // Remove MIME from end
                                section = section.Substring(0,section.Length - "MIME".Length);

                                sectionType = "MIME";
                                messageItems = IMAP_MessageItems_enum.Header;
                            }

                            // Remove last ., if there is any
                            if(section.EndsWith(".")){
                                section = section.Substring(0,section.Length - 1);
                            }

                            // MimePartsSepcifier is specified, validate it. It can contain numbers only.
                            if(section.Length > 0){
                                // Now we certainly need full message, because nested mime parts wanted
                                messageItems |= IMAP_MessageItems_enum.Message;

                                string[] sectionParts = section.Split('.');
                                foreach(string sectionPart in sectionParts){
                                    if(!Core.IsNumber(sectionPart)){
                                        this.Socket.WriteLine(cmdTag + " BAD Invalid BODY[<section>] argument. Invalid <section>: " + section);
                                        return;
                                    }
                                }

                                mimePartsSpecifier = section;
                            }
                        }
                        else{
                            messageItems |= IMAP_MessageItems_enum.Message;
                        }

                        long startPosition = -1;
                        long length = -1;
                        // See if partial fetch
                        if(argsReader.StartsWith("<")){
                            /* <partial> syntax:
                                    startPosition[.endPosition]
                            */

                            // Read partial value between <>
                            string partial = "";
                            try{
                                partial = argsReader.ReadParenthesized();
                            }
                            catch{
                                this.Socket.WriteLine(cmdTag + " BAD Invalid BODY[]<start[.length]>, closing > parenthesize is missing !");
                                return;
                            }

                            string[] start_length = partial.Split('.');

                            // Validate <partial>
                            if(start_length.Length == 0 || start_length.Length > 2 || !Core.IsNumber(start_length[0]) || (start_length.Length == 2 && !Core.IsNumber(start_length[1]))){
                                this.Socket.WriteLine(cmdTag + " BAD Invalid BODY[]<partial> argument. Invalid <partial>: " + partial);
                                return;
                            }

                            startPosition = Convert.ToInt64(start_length[0]);
                            if(start_length.Length == 2){
                                length = Convert.ToInt64(start_length[1]);
                            }
                        }

                        // object[] structure for BODY[]
                        //	fetchFlagName
                        //	isPeek
                        //	mimePartsSpecifier
                        //  originalSectionValue
                        //	sectionType
                        //	sectionArgs
                        //	startPosition
                        //	length
                        fetchFlags.Add(new object[]{"BODY[]",peek,mimePartsSpecifier,originalSectionValue,sectionType,sectionArgs,startPosition,length});
                    }
                    // BODY
                    else{
                        fetchFlags.Add(new object[]{"BODY"});
                        messageItems |= IMAP_MessageItems_enum.BodyStructure;
                    }
                }

                #endregion

                #region ENVELOPE

                // ENVELOPE
                else if(argsReader.StartsWith("ENVELOPE")){
                    argsReader.ReadSpecifiedLength("ENVELOPE".Length);

                    fetchFlags.Add(new object[]{"ENVELOPE"});
                    messageItems |= IMAP_MessageItems_enum.Envelope;
                }

                #endregion

                #region FLAGS

                // FLAGS
                //	The flags that are set for this message.
                else if(argsReader.StartsWith("FLAGS")){
                    argsReader.ReadSpecifiedLength("FLAGS".Length);

                    fetchFlags.Add(new object[]{"FLAGS"});
                }

                #endregion

                #region INTERNALDATE

                // INTERNALDATE
                else if(argsReader.StartsWith("INTERNALDATE")){
                    argsReader.ReadSpecifiedLength("INTERNALDATE".Length);

                    fetchFlags.Add(new object[]{"INTERNALDATE"});
                }

                #endregion

                #region RFC822.HEADER

                // RFC822.HEADER
                else if(argsReader.StartsWith("RFC822.HEADER")){
                    argsReader.ReadSpecifiedLength("RFC822.HEADER".Length);

                    fetchFlags.Add(new object[]{"RFC822.HEADER"});
                    messageItems |= IMAP_MessageItems_enum.Header;
                }

                #endregion

                #region RFC822.SIZE

                // RFC822.SIZE
                //	The [RFC-2822] size of the message.
                else if(argsReader.StartsWith("RFC822.SIZE")){
                    argsReader.ReadSpecifiedLength("RFC822.SIZE".Length);

                    fetchFlags.Add(new object[]{"RFC822.SIZE"});
                }

                #endregion

                #region RFC822.TEXT

                // RFC822.TEXT
                else if(argsReader.StartsWith("RFC822.TEXT")){
                    argsReader.ReadSpecifiedLength("RFC822.TEXT".Length);

                    fetchFlags.Add(new object[]{"RFC822.TEXT"});
                    messageItems |= IMAP_MessageItems_enum.Message;
                }

                #endregion

                #region RFC822

                // RFC822 NOTE: RFC822 must be below RFC822.xxx or is parsed wrong !
                else if(argsReader.StartsWith("RFC822")){
                    argsReader.ReadSpecifiedLength("RFC822".Length);

                    fetchFlags.Add(new object[]{"RFC822"});
                    messageItems |= IMAP_MessageItems_enum.Message;
                }

                #endregion

                #region UID

                // UID
                //	The unique identifier for the message.
                else if(argsReader.StartsWith("UID")){
                    argsReader.ReadSpecifiedLength("UID".Length);

                    fetchFlags.Add(new object[]{"UID"});
                }

                #endregion

                // This must be unknown fetch flag
                else{
                    this.Socket.WriteLine(cmdTag + " BAD Invalid fetch-items argument. Unkown part starts from: " + argsReader.SourceString);
                    return;
                }
            }

            #endregion

            // ToDo: ??? But non of the servers do it ?
            // The server should respond with a tagged BAD response to a command that uses a message
            // sequence number greater than the number of messages in the selected mailbox.  This
            // includes "*" if the selected mailbox is empty.
            //	if(m_Messages.Count == 0 || ){
            //		SendData(cmdTag + " BAD Sequence number greater than the number of messages in the selected mailbox !\r\n");
            //		return;
            //	}

            // Create buffered writer, so we make less network calls.
            SocketBufferedWriter bufferedWriter = new SocketBufferedWriter(this.Socket);

            for(int i=0;i<m_pSelectedFolder.Messages.Count;i++){
                IMAP_Message msg = m_pSelectedFolder.Messages[i];

                // For UID FETCH we must compare UIDs and for normal FETCH message numbers.
                bool sequenceSetContains = false;
                if(uidFetch){
                    sequenceSetContains = sequenceSet.Contains(msg.UID);
                }
                else{
                    sequenceSetContains = sequenceSet.Contains(i + 1);
                }

                if(sequenceSetContains){
                    IMAP_eArgs_MessageItems eArgs = null;
                    // Get message items only if they are needed.
                    if(messageItems != IMAP_MessageItems_enum.None){
                        // Raise event GetMessageItems to get all neccesary message itmes
                        eArgs = m_pServer.OnGetMessageItems(this,msg,messageItems);

                        // Message doesn't exist any more, notify email client.
                        if(!eArgs.MessageExists){
                            bufferedWriter.Write("* " + msg.SequenceNo + " EXPUNGE");
                            m_pSelectedFolder.Messages.Remove(msg);
                            i--;
                            continue;
                        }
                        try{
                            // Ensure that all requested items were provided.
                            eArgs.Validate();
                        }
                        catch(Exception x){
                            m_pServer.OnSysError(x.Message,x);
                            this.Socket.WriteLine(cmdTag + " NO Internal IMAP server component error: " + x.Message);
                            return;
                        }
                    }

                    // Write fetch start data "* msgNo FETCH ("
                    bufferedWriter.Write("* " + (i + 1) + " FETCH (");

                    IMAP_MessageFlags msgFlagsOr = msg.Flags;
                    // Construct reply here, based on requested fetch items
                    int nCount = 0;
                    foreach(object[] fetchFlag in fetchFlags){
                        string fetchFlagName = (string)fetchFlag[0];

                        #region BODY

                        // BODY
                        if(fetchFlagName == "BODY"){
                            // Sets \seen flag
                            msg.SetFlags(msg.Flags | IMAP_MessageFlags.Seen);

                            // BODY ()
                            bufferedWriter.Write("BODY " + eArgs.BodyStructure);
                        }

                        #endregion

                        #region BODY[], BODY.PEEK[]

                        // BODY[<section>]<<partial>>, BODY.PEEK[<section>]<<partial>>
                        else if(fetchFlagName == "BODY[]"){
                            // Force to write all buffered data.
                            bufferedWriter.Flush();

                            // object[] structure for BODY[]
                            //	fetchFlagName
                            //	isPeek
                            //	mimePartsSpecifier
                            //  originalSectionValue
                            //	sectionType
                            //	sectionArgs
                            //	startPosition
                            //	length
                            bool   isPeek               = (bool)fetchFlag[1];
                            string mimePartsSpecifier   = (string)fetchFlag[2];
                            string originalSectionValue = (string)fetchFlag[3];
                            string sectionType          = (string)fetchFlag[4];
                            string sectionArgs          = (string)fetchFlag[5];
                            long   startPosition        = (long)fetchFlag[6];
                            long   length               = (long)fetchFlag[7];

                            // Difference between BODY[] and BODY.PEEK[] is that .PEEK won't set seen flag
                            if(!isPeek){
                                // Sets \seen flag
                                msg.SetFlags(msg.Flags | IMAP_MessageFlags.Seen);
                            }

                            /* Section value:
                                ""                - entire message
                                HEADER            - message header
                                HEADER.FIELDS     - message header fields
                                HEADER.FIELDS.NOT - message header fields except requested
                                TEXT              - message text
                                MIME              - same as header, different response
                            */
                            Stream dataStream = null;
                            if(sectionType == "" && mimePartsSpecifier == ""){
                                dataStream = eArgs.MessageStream;
                            }
                            else{
                                LumiSoft.Net.Mime.Mime parser = null;
                                try{
                                    if(eArgs.MessageStream == null){
                                        parser = LumiSoft.Net.Mime.Mime.Parse(eArgs.Header);
                                    }
                                    else{
                                        parser = LumiSoft.Net.Mime.Mime.Parse(eArgs.MessageStream);
                                    }
                                }
                                // Invalid message, parsing failed
                                catch{
                                    parser = LumiSoft.Net.Mime.Mime.CreateSimple(new AddressList(),new AddressList(),"BAD Message","This is BAD message, mail server failed to parse it !","");
                                }
                                MimeEntity currentEntity = parser.MainEntity;
                                // Specific mime entity requested, get it
                                if(mimePartsSpecifier != ""){
                                    currentEntity = FetchHelper.GetMimeEntity(parser,mimePartsSpecifier);
                                }

                                if(currentEntity != null){
                                    if(sectionType == "HEADER"){
                                        dataStream = new MemoryStream(FetchHelper.GetMimeEntityHeader(currentEntity));
                                    }
                                    else if(sectionType == "HEADER.FIELDS"){
                                        dataStream = new MemoryStream(FetchHelper.ParseHeaderFields(sectionArgs,currentEntity));
                                    }
                                    else if(sectionType == "HEADER.FIELDS.NOT"){
                                        dataStream = new MemoryStream(FetchHelper.ParseHeaderFieldsNot(sectionArgs,currentEntity));
                                    }
                                    else if(sectionType == "TEXT"){
                                        try{
                                            dataStream = new MemoryStream(currentEntity.DataEncoded);
                                        }
                                        catch{ // This probably multipart entity, data isn't available
                                        }
                                    }
                                    else if(sectionType == "MIME"){
                                        dataStream = new MemoryStream(FetchHelper.GetMimeEntityHeader(currentEntity));
                                    }
                                    else if(sectionType == ""){
                                        try{
                                            dataStream = new MemoryStream(currentEntity.DataEncoded);
                                        }
                                        catch{ // This probably multipart entity, data isn't available
                                        }
                                    }
                                }
                            }

                            // Partial fetch. Reports <origin position> in fetch reply.
                            if(startPosition > -1){
                                if(dataStream == null){
                                    this.Socket.Write("BODY[" + originalSectionValue + "]<" + startPosition.ToString() + "> \"\"\r\n");
                                }
                                else{
                                    long lengthToSend = length;
                                    if(lengthToSend == -1){
                                        lengthToSend = (dataStream.Length - dataStream.Position) - startPosition;
                                    }
                                    if((lengthToSend + startPosition) > (dataStream.Length - dataStream.Position)){
                                        lengthToSend = (dataStream.Length - dataStream.Position) - startPosition;
                                    }

                                    if(startPosition >= (dataStream.Length - dataStream.Position)){
                                        this.Socket.Write("BODY[" + originalSectionValue + "]<" + startPosition.ToString() + "> \"\"\r\n");
                                    }
                                    else{
                                        this.Socket.Write("BODY[" + originalSectionValue + "]<" + startPosition.ToString() + "> {" + lengthToSend + "}\r\n");
                                        dataStream.Position += startPosition;
                                        this.Socket.Write(dataStream,lengthToSend);
                                    }
                                }
                            }
                            // Normal fetch
                            else{
                                if(dataStream == null){
                                    this.Socket.Write("BODY[" + originalSectionValue + "] \"\"\r\n");
                                }
                                else{
                                    this.Socket.Write("BODY[" + originalSectionValue + "] {" + (dataStream.Length - dataStream.Position) + "}\r\n");
                                    this.Socket.Write(dataStream);
                                }
                            }
                        }

                        #endregion

                        #region BODYSTRUCTURE

                        // BODYSTRUCTURE
                        else if(fetchFlagName == "BODYSTRUCTURE"){
                            bufferedWriter.Write("BODYSTRUCTURE " + eArgs.BodyStructure);
                        }

                        #endregion

                        #region ENVELOPE

                        // ENVELOPE
                        else if(fetchFlagName == "ENVELOPE"){
                            bufferedWriter.Write("ENVELOPE " + eArgs.Envelope);
                        }

                        #endregion

                        #region FLAGS

                        // FLAGS
                        else if(fetchFlagName == "FLAGS"){
                            bufferedWriter.Write("FLAGS (" + msg.FlagsString + ")");
                        }

                        #endregion

                        #region INTERNALDATE

                        // INTERNALDATE
                        else if(fetchFlagName == "INTERNALDATE"){
                            // INTERNALDATE "date"
                            bufferedWriter.Write("INTERNALDATE \"" + IMAP_Utils.DateTimeToString(msg.InternalDate) + "\"");
                        }

                        #endregion

                        #region RFC822

                        // RFC822
                        else if(fetchFlagName == "RFC822"){
                            // Force to write all buffered data.
                            bufferedWriter.Flush();

                            // Sets \seen flag
                            msg.SetFlags(msg.Flags | IMAP_MessageFlags.Seen);

                            // RFC822 {size}
                            // msg data
                            this.Socket.Write("RFC822 {" + eArgs.MessageSize.ToString() + "}\r\n");
                            this.Socket.Write(eArgs.MessageStream);
                        }

                        #endregion

                        #region RFC822.HEADER

                        // RFC822.HEADER
                        else if(fetchFlagName == "RFC822.HEADER"){
                            // Force to write all buffered data.
                            bufferedWriter.Flush();

                            // RFC822.HEADER {size}
                            // msg header data
                            this.Socket.Write("RFC822.HEADER {" + eArgs.Header.Length + "}\r\n");
                            this.Socket.Write(eArgs.Header);
                        }

                        #endregion

                        #region RFC822.SIZE

                        // RFC822.SIZE
                        else if(fetchFlagName == "RFC822.SIZE"){
                            // RFC822.SIZE size
                            bufferedWriter.Write("RFC822.SIZE " + msg.Size);
                        }

                        #endregion

                        #region RFC822.TEXT

                        // RFC822.TEXT
                        else if(fetchFlagName == "RFC822.TEXT"){
                            // Force to write all buffered data.
                            bufferedWriter.Flush();

                            // Sets \seen flag
                            msg.SetFlags(msg.Flags | IMAP_MessageFlags.Seen);

                            //--- Find body text entity ------------------------------------//
                            LumiSoft.Net.Mime.Mime parser = LumiSoft.Net.Mime.Mime.Parse(eArgs.MessageStream);
                            MimeEntity bodyTextEntity = null;
                            if(parser.MainEntity.ContentType == MediaType_enum.NotSpecified){
                                if(parser.MainEntity.DataEncoded != null){
                                    bodyTextEntity = parser.MainEntity;
                                }
                            }
                            else{
                                MimeEntity[] entities = parser.MimeEntities;
                                foreach(MimeEntity entity in entities){
                                    if(entity.ContentType == MediaType_enum.Text_plain){
                                        bodyTextEntity = entity;
                                        break;
                                    }
                                }
                            }
                            //----------------------------------------------------------------//

                            // RFC822.TEXT {size}
                            // msg text
                            byte[] data = null;
                            if(bodyTextEntity != null){
                                data = bodyTextEntity.DataEncoded;
                            }
                            else{
                                data = System.Text.Encoding.ASCII.GetBytes("");
                            }

                            this.Socket.Write("RFC822.TEXT {" + data.Length + "}\r\n");
                            this.Socket.Write(data);
                        }

                        #endregion

                        #region UID

                        // UID
                        else if(fetchFlagName == "UID"){
                            bufferedWriter.Write("UID " + msg.UID);
                        }

                        #endregion

                        nCount++;

                        // Write fetch item separator data " "
                        // We don't write it for last item
                        if(nCount < fetchFlags.Count){
                            bufferedWriter.Write(" ");
                        }
                    }

                    // Write fetch end data ")"
                    bufferedWriter.Write(")\r\n");

                    // Free event args, close message stream, ... .
                    if(eArgs != null){
                        eArgs.Dispose();
                    }

                    // Set message flags here if required or changed
                    if(((int)IMAP_MessageFlags.Recent & (int)msg.Flags) != 0 || msgFlagsOr != msg.Flags){
                        msg.SetFlags(msg.Flags & ~IMAP_MessageFlags.Recent);

                        m_pServer.OnStoreMessageFlags(this,msg);
                    }
                }
            }

            // Force to write all buffered data.
            bufferedWriter.Flush();

            this.Socket.WriteLine(cmdTag + " OK FETCH completed in " + ((DateTime.Now.Ticks - startTime) / (decimal)10000000).ToString("f2") + " seconds");
        }