Menu

customer headers in Message class

2004-02-24
2004-02-24
  • Wilson Chan

    Wilson Chan - 2004-02-24

    support for custom headers is prefered:

            private string _received=null;
            private string _xMailer=null;
            private string _xOriginatingIP=null;
            private string _xPriority=null;
            private string _xMSMailPriority=null;
            private string _importance=null;
            private string _xOriginalArrivalTime=null;
            private string _attachmentboundry2=null;       
            private string _dispositionNotificationTo=null;

            public string DispositionNotificationTo
            {
                get
                {
                    return _dispositionNotificationTo;
                }
            }

            public string Received
            {
                get
                {
                    return _received;
                }
            }

            public string XMailer
            {
                get
                {
                    return _xMailer;
                }
            }

            public string XOriginatingIP
            {
                get
                {
                    return _xOriginatingIP;
                }
            }

            public string XPriority
            {
                get
                {
                    return _xPriority;
                }
            }

            public string XMSMailPriority
            {
                get
                {
                    return _xMSMailPriority;
                }
            }

            public string Importance
            {
                get
                {
                    return _importance;
                }
            }

            public string XOriginalArrivalTime
            {
                get
                {
                    return _xOriginalArrivalTime;
                }
            }

            public string ContentCharset
            {
                get
                {
                    return _contentCharset;
                }
            }

            public string AttachmentBoundry2
            {
                get
                {
                    return _attachmentboundry2;
                }
            }

            internal Message(string wMessage, bool onlyHeader)
            {
                _rawMessage=wMessage;
                StringReader reader=new StringReader(wMessage);
                StringBuilder builder=new StringBuilder();
                string temp=null;
                while( (temp=reader.ReadLine()) !=null && temp.Trim()!="")
                {   
                    builder.Append(temp);
                    parseHeader(reader,temp);               
                }

                _rawHeader=builder.ToString();
               
                SetAttachmentBoundry2(_rawHeader);

                _rawMessageBody=reader.ReadToEnd().Trim();

                if(_contentLength==0)
                    _contentLength=wMessage.Length;//_rawMessageBody.Length;

                if(onlyHeader==false)
                {
                    if(_hasAttachment==true && _attachmentboundry!=null)
                    {
                        set_attachmentCount();
                        set_attachments();

                        if (this.Attachments.Count>0)
                        {
                            Attachment at=this.GetAttachment(0);
                            if(at.NotAttachment)
                                this.GetMessageBody(at.DecodeAttachmentAsText());                       
                            else
                            {}
                        }
                        else
                        {}
                    }
                    else
                    {
                        //_messageBody=GetTextMessage(_rawMessage);
                        GetMessageBody(_rawMessageBody);
                    }
                }
            }

            public void GetMessageBody(string Buffer)
            {
                int end, begin;
                string body;
                string encoding="";
               
                begin = end = 0;
                _messageBody.Clear();

                try
                {
                    if(_contentType.IndexOf("digest") >= 0)
                    {
                        // this is a digest method
                        //ParseDigestMessage(Buffer);
                        _messageBody.Add(Buffer);
                    }
                    else if(_attachmentboundry2==null)
                    {
                        body=Buffer;
                        if(Utility.IsQuotedPrintable(_contentTransferEncoding))
                        {
                            body=DecodeQP.ConvertHexContent(body);
                        }
                        else if(Utility.IsBase64(_contentTransferEncoding))
                        {
                            body=Utility.deCodeB64s(Utility.RemoveNonB64(body));
                        }
                        _messageBody.Add(body);
                    }
                    else
                    {
                        begin =0;
                        //int intBodies=0;
                        while(begin!=-1)
                        {
                            // find "\r\n\r\n" denoting end of header
                            begin = Buffer.IndexOf("--" + _attachmentboundry2,begin);
                            if(begin!=-1)
                            {
                                encoding=Utility.GetContentTransferEncoding(Buffer,begin);

                                begin = Buffer.IndexOf("\r\n\r\n",begin+1);//Buffer.LastIndexOfAny(ALPHABET.ToCharArray());
                                //if((end = Buffer.LastIndexOfAny(NON_WHITE.ToCharArray())) < 0)
                               
                                end = Buffer.IndexOf("--" + _attachmentboundry2,begin+1);
                                // find end of text
                                //end = Buffer.IndexOf("\r\n--" + _attachmentboundry2,begin+1);//Buffer.LastIndexOfAny(ALPHABET.ToCharArray());

                                if(begin!=-1)
                                {
                                    if(end!=-1)
                                    {
                                        begin += 4;
                                        if (this._contentEncoding!=null && this._contentEncoding.IndexOf("8bit")!=-1)
                                            body=Utility.Change(Buffer.Substring(begin, end - begin-2 ),_contentCharset);
                                        else
                                            body=Buffer.Substring(begin, end - begin-2);
                       
                                        //intBodies++;
                                        // find "\r\n\r\n" denoting end of header
                                        //                                begin = Buffer.IndexOf("\r\n\r\n",begin);
                                        //                                // find end of text
                                        //                                if(begin!=-1)
                                        //                                    end = Buffer.IndexOf("\r\n--" + _attachmentboundry2,begin+1);
                                        //                                else
                                        //                                    break;
                                    }
                                    else
                                    {
                                        body=Buffer.Substring(begin);
                                    }

                                    if(Utility.IsQuotedPrintable(encoding))
                                        _messageBody.Add(DecodeQP.ConvertHexContent(body));
                                    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
                                {
                                    //_messageBody[0]=Buffer;
                                    break;
                                }
                            }
                            else
                            {
                                //_messageBody[0]=Buffer;
                                if(_messageBody.Count==0)
                                {
                                    //_messageBody.Add(Utility.deCodeB64s(Buffer));
                                    _messageBody.Add(Buffer);
                                }
                                break;
                            }
                        }
                    }
                }
                catch(Exception e)
                {
                    Utility.LogError("GetMessageBody():"+e.Message);
                    _messageBody.Add(Utility.deCodeB64s(Buffer));
                }
                if(_messageBody.Count>1)
                    _html=true;
            }

    //        public string GetTextMessage(string buffer)
    //        {
    //            // find "\r\n\r\n" denoting end of header
    //            int start=buffer.IndexOf("\r\n\r\n")+4;
    //            int end=buffer.LastIndexOf("\r\n.\r\n");
    //            //change charset if contentTransferEncoding is 8bit
    //            if(start!=-1&&end!=-1)
    //            {
    //                if (this._contentEncoding!=null && this._contentEncoding.IndexOf("8bit")!=-1)
    //                    return Utility.Change(buffer.Substring(start,end-start),_contentCharset);
    //                else
    //                    return buffer.Substring(start,end-start);           
    //            }
    //            else
    //                return buffer;
    //        }

            public bool IsMIMEMailFile(Attachment attItem)
            {
                try
                {
                    return (attItem.ContentFileName.ToLower().EndsWith(".eml".ToLower()));
                }
                catch(Exception e)
                {
                    return false;
                }
            }

            /// <summary>
            /// save attachment to file
            /// </summary>
            /// <param name="attItem">Attachment</param>
            /// <param name="strFileName">File to be saved to</param>
            /// <returns></returns>
            public bool SaveAttachment(Attachment attItem, string strFileName)
            {
                try
                {
    //                FileStream fs=File.Create(strFileName);
    //                byte[] da;
    //                if(attItem.ContentFileName.Length>0)
    //                {
    //                    da=attItem.DecodedAttachment;
    //                }
    //                else
    //                {
    //                    this.GetMessageBody(attItem.DecodeAttachmentAsText());
    //                    da=Encoding.Default.GetBytes((string)this.MessageBody[this.MessageBody.Count-1]);
    //                }
    //                fs.Write(da,0,da.Length);
    //                fs.Close();
    //                return true;
                    byte[] da;
                    if(attItem.ContentFileName.Length>0)
                    {
                        da=attItem.DecodedAttachment;
                    }
                    else
                    {
                        this.GetMessageBody(attItem.DecodeAttachmentAsText());
                        da=Encoding.Default.GetBytes((string)this.MessageBody[this.MessageBody.Count-1]);
                    }
                    return Utility.SaveByteContentToFile(da,strFileName);
                }
                catch(Exception e)
                {
                    Utility.LogError("SaveAttachment():"+e.Message);
                    return false;
                }
            }

            /// <summary>
            /// Parse the message for attachment boundry and calculate number of _attachments
            /// based on that
            /// </summary>
            private void set_attachmentCount()
            {
                int indexOf_attachmentboundry=0;

                while( (indexOf_attachmentboundry=_rawMessageBody.IndexOf(_attachmentboundry,indexOf_attachmentboundry+1))>0)
                {
                    _attachmentCount++;
                }
                _attachmentCount--;
            }

            /// <summary>
            /// set attachments
            /// </summary>
            private void set_attachments()
            {
                int indexOf_attachmentstart=0;
                int indexOfAttachmentEnd=0;

                SetAttachmentBoundry2(_rawMessageBody);
               
                while(true)
                {
                    indexOf_attachmentstart=_rawMessageBody.IndexOf(_attachmentboundry,indexOf_attachmentstart+1)+_attachmentboundry.Length;
                    if(indexOf_attachmentstart<0)return;

                    indexOfAttachmentEnd=_rawMessageBody.IndexOf(_attachmentboundry,indexOf_attachmentstart+1);               
                    if(indexOfAttachmentEnd<0)return;

                    string temp=_rawMessageBody.Substring(indexOf_attachmentstart,(indexOfAttachmentEnd-indexOf_attachmentstart-2));           
                    _attachments.Add(new Attachment(temp.Trim()));
                }
            }

            private void setMail(string rawData)
            {           

            }

            /// <summary>
            /// Set alternative attachment boundry
            /// </summary>
            /// <param name="buffer">raw message</param>
            private void SetAttachmentBoundry2(string buffer)
            {
                int indexOfAttachmentBoundry2Begin=0;
                int indexOfAttachmentBoundry2End=0;
                indexOfAttachmentBoundry2Begin=buffer.ToLower().IndexOf("Multipart/Alternative".ToLower());
                if(indexOfAttachmentBoundry2Begin!=-1)
                {
                    indexOfAttachmentBoundry2Begin=buffer.IndexOf("boundary=\&quot;");
                    indexOfAttachmentBoundry2End=buffer.IndexOf("\&quot;",indexOfAttachmentBoundry2Begin+10);
                    if(indexOfAttachmentBoundry2Begin!=-1&&indexOfAttachmentBoundry2End!=-1)
                        _attachmentboundry2=buffer.Substring(indexOfAttachmentBoundry2Begin+10,indexOfAttachmentBoundry2End-indexOfAttachmentBoundry2Begin-10).Trim();
                }
            }

            public bool SaveToMIMEEmailFile(string file)
            {
                return Utility.SaveByteContentToFile(Encoding.Default.GetBytes(_rawMessage),file);
            }

            /// <summary>
            /// Parse the headers populating respective member fields
            /// </summary>
            /// <param name="temp"></param>
            ///
            private void parseHeader(StringReader reader,string temp)
            {
                string []array=Utility.getHeadersValue(temp);       

                switch(array[0].ToUpper())
                {
                    case "TO":
                        _to=array[1].Split(',');
                        for(int i=0;i<_to.Length;i++)
                        {
                            _to[i]=_to[i].Trim();
                        }
                        break;

                    case "CC":
                        _cc=array[1].Split(',');                   
                        break;

                    case "BCC":
                        _bcc=array[1].Split(',');                   
                        break;

                    case "FROM":
                        int indexOfAB=array[1].LastIndexOf("<");
                        int indexOfEndAB=array[1].LastIndexOf(">");
                        _from=array[1];
                        _fromEmail=array[1];
                        if(indexOfAB>=0&&indexOfEndAB>=0)
                            {
                            _from=_from.Substring(0,indexOfAB-1);                   
                            if(_from.IndexOf("\&quot;")>=0)
                            {
                                _from=_from.Substring(1,_from.Length-2);
                            }
                            _fromEmail=_fromEmail.Substring(indexOfAB+1,indexOfEndAB-(indexOfAB+1));
                        }
                        _from=_from.Trim();
                        _from=Utility.deCode(_from);
                        _fromEmail=_fromEmail.Trim();                   
                        break;

                    case "RECEIVED":
                        _received=array[1].Trim();//temp.Split(':')[1].Trim();
                        break;

                    case "X-ORIGINATING-IP":
                        _xOriginatingIP=array[1].Trim();//temp.Split(':')[1].Trim();
                        break;

                    case "X-PRIORITY":
                        _xPriority=array[1].Trim();//temp.Split(':')[1].Trim();
                        break;

                    case "X-MSMAIL-PRIORITY":
                        _xMSMailPriority=array[1].Trim();//temp.Split(':')[1].Trim();
                        break;

                    case "IMPORTANCE":
                        _importance=array[1].Trim();//temp.Split(':')[1].Trim();
                        break;

                    case "X-MAILER":
                        _xMailer=array[1].Trim();//temp.Split(':')[1].Trim();
                        break;

                    case "DISPOSITION-NOTIFICATION-TO":
                        _dispositionNotificationTo=array[1].Trim();
                        break;

                    case "MIME-VERSION":
                        _mimeVersion=array[1].Trim();//temp.Split(':')[1].Trim();
                        break;

                    case "X-OriginalArrivalTime":
                        _xOriginalArrivalTime=array[1].Trim();//temp.Split(':')[1].Trim();
                        break;

                    case "SUBJECT":
                        _subject=array[1].Trim();//temp.Split(':')[1].Trim();
                        _subject=Utility.deCode(_subject);
                        break;
                   
                    case "RETURN-PATH":
                        _returnPath=array[1].Trim().Trim('>').Trim('<');//temp.Split(':')[1].Trim().Trim('>').Trim('<');
                        break;

                    case "MESSAGE-ID":
                        _messageID=array[1].Trim().Trim('>').Trim('<');//array[1].Trim().Trim('>').Trim('<');;
                        break;

                    case "DATE":
                        for(int i=1;i<array.Length;i++)
                        {
                            _date+=array[i];
                        }
                        _date=_date.Trim();
                        break;

                    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;

                        _contentType=array[1].Split(';')[0];
                        _contentType=_contentType.Trim();

                        int intCharset=_contentType.IndexOf("charset=");
                        if(intCharset!=-1)
                        {
                            int intPos=_contentType.IndexOf("\&quot;",intCharset+9);
                            _contentCharset=_contentType.Substring(intCharset+8,intPos-intCharset-8);
                        }

                        if(_contentType=="text/plain")
                            return;
                        else if(_contentType=="text/html")
                            _html=true;

                        if(array[1].Trim().Length==_contentType.Length+1)
                            _attachmentboundry=reader.ReadLine();
                        else
                            _attachmentboundry=array[1].Split(';')[1];

                        int indexOfQuote=_attachmentboundry.IndexOf("\&quot;");
                        int lastIndexOfQuote=_attachmentboundry.LastIndexOf("\&quot;");
                        if(indexOfQuote>=0&&lastIndexOfQuote>=0)
                        {
                            _attachmentboundry=_attachmentboundry.Substring(indexOfQuote+1,lastIndexOfQuote-(indexOfQuote+1));

                            _hasAttachment=true;
                        }
                       
                        break;
                }
            }

     
    • Wilson Chan

      Wilson Chan - 2004-02-24

      I also make major changes to parse the MIME content more properly

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.