/// <summary>
        /// Decodes a byte array into another byte array based upon the Content Transfer encoding
        /// </summary>
        /// <param name="messageBody">The byte array to decode into another byte array</param>
        /// <param name="contentTransferEncoding">The <see cref="ContentTransferEncoding"/> of the byte array</param>
        /// <returns>A byte array which comes from the <paramref name="contentTransferEncoding"/> being used on the <paramref name="messageBody"/></returns>
        /// <exception cref="ArgumentNullException">If <paramref name="messageBody"/> is <see langword="null"/></exception>
        /// <exception cref="ArgumentOutOfRangeException">Thrown if the <paramref name="contentTransferEncoding"/> is unsupported</exception>
        private static byte[] DecodeBody(byte[] messageBody, ContentTransferEncoding contentTransferEncoding)
        {
            if (messageBody == null)
            {
                throw new ArgumentNullException("messageBody");
            }

            switch (contentTransferEncoding)
            {
            case ContentTransferEncoding.QuotedPrintable:
                // If encoded in QuotedPrintable, everything in the body is in US-ASCII
                return(QuotedPrintable.DecodeContentTransferEncoding(Encoding.ASCII.GetString(messageBody)));

            case ContentTransferEncoding.Base64:
                // If encoded in Base64, everything in the body is in US-ASCII
                return(Base64.Decode(Encoding.ASCII.GetString(messageBody)));

            case ContentTransferEncoding.SevenBit:
            case ContentTransferEncoding.Binary:
            case ContentTransferEncoding.EightBit:
                // We do not have to do anything
                return(messageBody);

            default:
                throw new ArgumentOutOfRangeException("contentTransferEncoding");
            }
        }
Ejemplo n.º 2
0
        internal static void UpdateTransferEncoding(MimePart part, ContentTransferEncoding embeddedCte)
        {
            if (ContentTransferEncoding.EightBit == embeddedCte || ContentTransferEncoding.Binary == embeddedCte)
            {
                string value = (ContentTransferEncoding.EightBit == embeddedCte) ? "8bit" : "binary";
                do
                {
                    ContentTransferEncoding contentTransferEncoding = part.ContentTransferEncoding;
                    if (ContentTransferEncoding.Binary != contentTransferEncoding && embeddedCte != contentTransferEncoding)
                    {
                        Header header = part.Headers.FindFirst(HeaderId.ContentTransferEncoding);
                        if (header == null)
                        {
                            header = Header.Create(HeaderId.ContentTransferEncoding);
                            part.Headers.AppendChild(header);
                        }
                        header.Value = value;
                    }
                    part = (part.Parent as MimePart);
                }while (part != null);
                return;
            }
            Header header2 = part.Headers.FindFirst(HeaderId.ContentTransferEncoding);

            if (header2 != null)
            {
                header2.RemoveFromParent();
            }
        }
Ejemplo n.º 3
0
        // Token: 0x0600032B RID: 811 RVA: 0x00012138 File Offset: 0x00010338
        private bool IsInlineBoundary(byte[] data, int line, int nextNL, int end, out int nextBoundaryLevel, out bool nextBoundaryEnd)
        {
            ContentTransferEncoding contentTransferEncoding = this.inlineFormat;

            if (contentTransferEncoding != ContentTransferEncoding.Unknown)
            {
                if (contentTransferEncoding == ContentTransferEncoding.UUEncode)
                {
                    if ((data[line] | 32) == 101 && nextNL - line >= 3 && MimeParser.IsUUEncodeEnd(data, line, nextNL))
                    {
                        nextBoundaryLevel = -100;
                        nextBoundaryEnd   = true;
                        return(true);
                    }
                }
            }
            else if ((data[line] | 32) == 98 && nextNL - line >= 11 && nextNL != end && MimeParser.IsUUEncodeBegin(data, line, nextNL))
            {
                nextBoundaryLevel = -100;
                nextBoundaryEnd   = false;
                return(true);
            }
            nextBoundaryLevel = -1;
            nextBoundaryEnd   = false;
            return(false);
        }
Ejemplo n.º 4
0
        void IMimeHandlerInternal.EndOfHeaders(string mediaType, ContentTransferEncoding cte, out PartContentParseOptionInternal partContentParseOption)
        {
            PartContentParseOption partContentParseOption2;

            this.handler.EndOfHeaders(mediaType, cte, out partContentParseOption2);
            partContentParseOption = (PartContentParseOptionInternal)partContentParseOption2;
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Content-Transfer filter for detecting MIME encoding.
        /// </summary>
        /// <param name="headerField">Header field name</param>
        /// <param name="value">Value of the field.</param>
        /// <returns>Filtered value.</returns>
        protected string ContentTransferFilter(string headerField, string value)
        {
            switch (value.ToLower())
            {
            case "base64":
                transferEncoding = ContentTransferEncoding.Base64;
                break;

            case "quoted-printable":
                transferEncoding = ContentTransferEncoding.QoutedPrintable;
                break;

            case "binary":
                transferEncoding = ContentTransferEncoding.Binary;
                break;

            case "8bit":
                transferEncoding = ContentTransferEncoding.EightBit;
                break;

            case "7bit":
                transferEncoding = ContentTransferEncoding.SevenBit;
                break;

            default:
                transferEncoding = ContentTransferEncoding.Unknown;
                break;
            }
            return(value);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Encode bytes to specified MIME encoding string.
        /// </summary>
        /// <param name="bytes">Bytes to encode.</param>
        /// <param name="offset">Offset in bytes</param>
        /// <param name="length">Length of bytes</param>
        /// <param name="contentEncoding">MIME Encoding.</param>
        /// <param name="breakLines">Split in lines if true.</param>
        /// <returns>MIME encoded byte stream.</returns>
        public static IEnumerable <byte> Encode(byte[] bytes, int offset, int length,
                                                ContentTransferEncoding contentEncoding, bool breakLines)
        {
            var result = new List <byte>(1024);

            switch (contentEncoding)
            {
            // TODO: is ASCII okay?
            case ContentTransferEncoding.Base64:
                result.AddRange(Encoding.ASCII.GetBytes(
                                    Convert.ToBase64String(bytes, offset, length, breakLines ?
                                                           Base64FormattingOptions.InsertLineBreaks : Base64FormattingOptions.None)));
                break;

            // TODO: is ASCII okay?
            case ContentTransferEncoding.QoutedPrintable:
                result.AddRange(Encoding.ASCII.GetBytes(
                                    ToQuotedPrintableString(bytes, offset, length, breakLines)));
                break;

            case ContentTransferEncoding.SevenBit:
            // TODO: cut 8th bit or not?
            case ContentTransferEncoding.EightBit:
            case ContentTransferEncoding.Binary:
            default:
                // split per 1000 symbols (including trailing CRLF)
                //writer.Write(encoding.GetBytes(split998.Replace(body.ToString(), "$&" + Util.CRLF)));
                for (int i = offset; i < offset + length; i++)
                {
                    result.Add(bytes[i]);
                }
                break;
            }
            return(result);
        }
Ejemplo n.º 7
0
        private Stream GetContentStream(ContentTransferEncoding contentTransferEncoding)
        {
            if (this.isInContent)
            {
                throw new InvalidOperationException(SR.GetString("MailWriterIsInContent"));
            }
            this.isInContent = true;
            this.bufferBuilder.Append(CRLF);
            this.Flush();
            Stream stream = this.stream;

            if (contentTransferEncoding == ContentTransferEncoding.SevenBit)
            {
                stream = new SevenBitStream(stream);
            }
            else if (contentTransferEncoding == ContentTransferEncoding.QuotedPrintable)
            {
                stream = new QuotedPrintableStream(stream, this.lineLength);
            }
            else if (contentTransferEncoding == ContentTransferEncoding.Base64)
            {
                stream = new Base64Stream(stream, this.lineLength);
            }
            ClosableStream stream2 = new ClosableStream(stream, this.onCloseHandler);

            this.contentStream = stream2;
            return(stream2);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Encode bytes to specified MIME encoding string.
        /// </summary>
        /// <param name="bytes">Bytes to encode.</param>
        /// <param name="contentEncoding">MIME Encoding.</param>
        /// <param name="breakLines">Split in lines if true.</param>
        /// <returns>MIME encoded byte stream.</returns>
        public static IEnumerable <byte> Encode(IEnumerable <byte> bytes, ContentTransferEncoding contentEncoding,
                                                bool breakLines)
        {
            var array = bytes is byte[] ? (byte[])bytes : new List <byte>(bytes).ToArray();

            return(Encode(array, 0, array.Length, contentEncoding, breakLines));
        }
Ejemplo n.º 9
0
 private void ParseValue()
 {
     if (this.contentTransferEncodingValue == null)
     {
         int num = 0;
         this.contentTransferEncodingValue = ((base.Value.Length == 0) ? base.Value : ((base.Value[0] == '"') ? MailBnfHelper.ReadQuotedString(base.Value, ref num, null) : MailBnfHelper.ReadToken(base.Value, ref num, null)));
         string a;
         if ((a = this.contentTransferEncodingValue) != null)
         {
             if (a == "7bit")
             {
                 this.contentTransferEncoding = ContentTransferEncoding.SevenBit;
                 return;
             }
             if (a == "8bit")
             {
                 this.contentTransferEncoding = ContentTransferEncoding.EightBit;
                 return;
             }
             if (a == "binary")
             {
                 this.contentTransferEncoding = ContentTransferEncoding.Binary;
                 return;
             }
         }
         this.contentTransferEncoding = ContentTransferEncoding.Other;
     }
 }
Ejemplo n.º 10
0
 /// <summary>
 /// Initializes new instance of the class and converts stream to base64 format and save
 /// </summary>
 /// <param name="stream"></param>
 /// <param name="allProperties"></param>
 /// <param name="encoding"></param>
 public File(Stream stream, FileInfo allProperties, ContentTransferEncoding encoding) : base(stream, encoding)
 {
     this.FilePath      = allProperties.FilePath;
     this.FolderPath    = allProperties.FolderPath;
     this.FileName      = allProperties.FileName;
     this.ServerAddress = allProperties.ServerAddress;
 }
Ejemplo n.º 11
0
        public static string DoDecode(string input, ContentTransferEncoding contentTransferEncoding, string charSet)
        {
            switch (contentTransferEncoding)
            {
                case ContentTransferEncoding.QuotedPrintable:
                    if (!string.IsNullOrEmpty((charSet)))
                        return QuotedPrintable.Decode(input, Encoding.GetEncoding(charSet), 0);

                    return QuotedPrintable.Decode(input);

                case ContentTransferEncoding.Base64:
                    return Base64.Decode(input);

                case ContentTransferEncoding.SevenBit:
                case ContentTransferEncoding.Binary:
                case ContentTransferEncoding.EightBit:
                    if (!string.IsNullOrEmpty(charSet))
                        return ChangeEncoding(input, charSet);

                    // Nothing needed to be done
                    return input;

                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
Ejemplo n.º 12
0
        public void TestContentTransferEncodingBinary()
        {
            const string contentTransferEncodingString =
                "binary";

            ContentTransferEncoding encoding = HeaderFieldParser.ParseContentTransferEncoding(contentTransferEncodingString);

            Assert.AreEqual(ContentTransferEncoding.Binary, encoding);
        }
Ejemplo n.º 13
0
 internal Stream GetContentStream(ContentTransferEncoding contentTransferEncoding)
 {
     if (this.isInContent)
     {
         throw new InvalidOperationException(SR.GetString("MailWriterIsInContent"));
     }
     this.isInContent = true;
     return(this.GetContentStream(contentTransferEncoding, null));
 }
Ejemplo n.º 14
0
        public void TestContentTransferEncodingBase64()
        {
            const string contentTransferEncodingString =
                "base64";

            ContentTransferEncoding encoding = HeaderFieldParser.ParseContentTransferEncoding(contentTransferEncodingString);

            Assert.AreEqual(ContentTransferEncoding.Base64, encoding);
        }
Ejemplo n.º 15
0
        public void TestContentTransferEncodingQuotedPrintable()
        {
            const string contentTransferEncodingString =
                "quoted-printable";

            ContentTransferEncoding encoding = HeaderFieldParser.ParseContentTransferEncoding(contentTransferEncodingString);

            Assert.AreEqual(ContentTransferEncoding.QuotedPrintable, encoding);
        }
Ejemplo n.º 16
0
        public void TestContentTransferEncoding7Bit()
        {
            const string contentTransferEncodingString =
                "7bit";

            ContentTransferEncoding encoding = HeaderFieldParser.ParseContentTransferEncoding(contentTransferEncodingString);

            Assert.AreEqual(ContentTransferEncoding.SevenBit, encoding);
        }
Ejemplo n.º 17
0
        public void TestContentTransferEncodingQoutedPrintableFunnyCase()
        {
            const string contentTransferEncodingString =
                "quOTed-pRinTabLE";

            ContentTransferEncoding encoding = HeaderFieldParser.ParseContentTransferEncoding(contentTransferEncodingString);

            Assert.AreEqual(ContentTransferEncoding.QuotedPrintable, encoding);
        }
 internal IAsyncResult BeginGetContentStream(ContentTransferEncoding contentTransferEncoding, AsyncCallback callback, object state)
 {
     MultiAsyncResult multiResult = new MultiAsyncResult(this, callback, state);
     Stream contentStream = this.GetContentStream(contentTransferEncoding, multiResult);
     if (!(multiResult.Result is Exception))
     {
         multiResult.Result = contentStream;
     }
     multiResult.CompleteSequence();
     return multiResult;
 }
Ejemplo n.º 19
0
        internal IAsyncResult BeginGetContentStream(ContentTransferEncoding contentTransferEncoding, AsyncCallback callback, object state)
        {
            MultiAsyncResult multiResult   = new MultiAsyncResult(this, callback, state);
            Stream           contentStream = this.GetContentStream(contentTransferEncoding, multiResult);

            if (!(multiResult.Result is Exception))
            {
                multiResult.Result = contentStream;
            }
            multiResult.CompleteSequence();
            return(multiResult);
        }
Ejemplo n.º 20
0
        public void TestInvalidContentTransferEncoding()
        {
            const string wrongContentTransferEncoding = "ISO-8859-1";

            ContentTransferEncoding encoding = HeaderFieldParser.ParseContentTransferEncoding(wrongContentTransferEncoding);

            Assert.NotNull(encoding);

            // We want the implementation to return the default encoding instead of the wrongly specified one
            const ContentTransferEncoding defaultEncoding = ContentTransferEncoding.SevenBit;

            Assert.AreEqual(defaultEncoding, encoding);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Get whole encoded header
        /// </summary>
        public byte[] Encode(Encoding encoding, ContentTransferEncoding mimeEncoding)
        {
            var builder = new StringBuilder(512);

            foreach (var key in AllKeys)
            {
                builder
                .Append(key)
                .Append(": ")
                .Append(this[key, encoding, mimeEncoding])
                .Append(Util.CRLF);
            }
            return(encoding.GetBytes(builder.ToString()));
        }
Ejemplo n.º 22
0
        internal static string GetRawFileName(MimePart part)
        {
            string result = null;

            if (Utility.TryGetFileNameFromHeader(part, HeaderId.ContentDisposition, "filename", ref result))
            {
                return(result);
            }
            if (Utility.TryGetFileNameFromHeader(part, HeaderId.ContentType, "name", ref result))
            {
                return(result);
            }
            string contentType = part.ContentType;

            if (contentType.Equals("message/rfc822", StringComparison.OrdinalIgnoreCase))
            {
                string result2 = "No Subject";
                Utility.TryGet822Subject(part, ref result2);
                return(result2);
            }
            if (contentType.Equals("multipart/appledouble", StringComparison.OrdinalIgnoreCase))
            {
                Utility.TryGetFileNameFromAppleDouble(part, ref result);
                return(result);
            }
            if (contentType.Equals("application/applefile", StringComparison.OrdinalIgnoreCase))
            {
                Utility.TryGetFileNameFromAppleFile(part, ref result);
                return(result);
            }
            ContentTransferEncoding contentTransferEncoding = part.ContentTransferEncoding;

            if (contentType.Equals("application/mac-binhex40", StringComparison.OrdinalIgnoreCase) || ContentTransferEncoding.BinHex == contentTransferEncoding)
            {
                Utility.TryGetFileNameFromBinHex(part, ref result);
                return(result);
            }
            if (ContentTransferEncoding.UUEncode == contentTransferEncoding)
            {
                Utility.TryGetFileNameFromUuencode(part, ref result);
                return(result);
            }
            if (Utility.TryGetFileNameFromHeader(part, HeaderId.ContentDescription, ref result))
            {
                return(result);
            }
            return(null);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Convert text to MIME encoded string with specified text and content transfer encodings
        /// </summary>
        /// <param name="text">Text to convert</param>
        /// <param name="header">true, if convert for MIME header</param>
        /// <param name="textEncoding">Target text encoding</param>
        /// <param name="contentEncoding">Content-Transfer encoding.
        ///		In header only base64 and quoted-printable encodings have meaning</param>
        /// <param name="breakLines">Split in lines if true.</param>
        /// <returns>MIME encoded text</returns>
        public static byte[] Encode(string text, Encoding textEncoding,
                                    ContentTransferEncoding contentEncoding, bool header, bool breakLines)
        {
            var builder      = new List <byte>(1024);
            var reallyHeader = false;

            if (header)
            {
                switch (contentEncoding)
                {
                case ContentTransferEncoding.Base64:
                case ContentTransferEncoding.QoutedPrintable:
                    reallyHeader = true;
                    builder.AddRange(textEncoding.GetBytes("=?"));
                    builder.AddRange(textEncoding.GetBytes(textEncoding.HeaderName));
                    builder.AddRange(textEncoding.GetBytes("?"));
                    builder.AddRange(textEncoding.GetBytes(
                                         (contentEncoding == ContentTransferEncoding.Base64) ? "b" : "q"));
                    builder.AddRange(textEncoding.GetBytes("?"));
                    break;
                }
            }

            switch (contentEncoding)
            {
            case ContentTransferEncoding.Base64:
            case ContentTransferEncoding.QoutedPrintable:
                builder.AddRange(Encode(textEncoding.GetBytes(text), contentEncoding, breakLines));
                break;

            case ContentTransferEncoding.SevenBit:
                // cut 8th bit
                builder.AddRange(Encoding.ASCII.GetBytes(text));
                break;

            default:
                builder.AddRange(textEncoding.GetBytes(text));
                break;
            }

            if (reallyHeader)
            {
                builder.AddRange(textEncoding.GetBytes("?="));
            }

            return(builder.ToArray());
        }
Ejemplo n.º 24
0
        internal void SetBody(string value)
        {
            if (ContentTransferEncoding.Is("quoted-printable"))
            {
                value = Utilities.DecodeQuotedPrintable(value, Utilities.ParseCharsetToEncoding(Charset));
            }
            else if (ContentTransferEncoding.Is("base64")
                     //only decode the content if it is a text document
                     && ContentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) &&
                     Utilities.IsValidBase64String(value))
            {
                value = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(value));
                ContentTransferEncoding = string.Empty;
            }

            Body = value;
        }
        public static TransferEncoding ToMimeTransferEncoding(this ContentTransferEncoding value)
        {
            switch (value)
            {
            case ContentTransferEncoding.Base64:
                return(TransferEncoding.Base64);

            case ContentTransferEncoding.QuotedPrintable:
                return(TransferEncoding.QuotedPrintable);

            case ContentTransferEncoding.SevenBit:
                return(TransferEncoding.SevenBit);

            default:
                return(TransferEncoding.Unknown);
            }
        }
Ejemplo n.º 26
0
 public byte[] GetData()
 {
     byte[] data;
     if (ContentTransferEncoding.Is("base64") && Utilities.IsValidBase64String(Body))
     {
         try {
             data = Convert.FromBase64String(Body);
         } catch (Exception) {
             data = System.Text.Encoding.UTF8.GetBytes(Body);
         }
     }
     else
     {
         data = System.Text.Encoding.UTF8.GetBytes(Body);
     }
     return(data);
 }
Ejemplo n.º 27
0
        public virtual byte[] GetData()
        {
            byte[] data;
            var    body = Body;

            if (ContentTransferEncoding.Is("base64") && Utilities.IsValidBase64String(ref body))
            {
                try {
                    data = Convert.FromBase64String(body);
                } catch (Exception) {
                    data = Encoding.GetBytes(body);
                }
            }
            else
            {
                data = Encoding.GetBytes(body);
            }
            return(data);
        }
Ejemplo n.º 28
0
            public override bool FilterHeaderList(HeaderList headerList, Stream stream)
            {
                Header header = headerList.FindFirst(HeaderId.ContentTransferEncoding);

                if (header != null)
                {
                    ContentTransferEncoding encodingType = MimePart.GetEncodingType(header.FirstRawToken);
                    if (encodingType == ContentTransferEncoding.EightBit || encodingType == ContentTransferEncoding.Binary)
                    {
                        ContentTypeHeader typeHeader = headerList.FindFirst(HeaderId.ContentType) as ContentTypeHeader;
                        bool flag;
                        bool flag2;
                        EightToSevenBitConverter.Analyse(typeHeader, out this.embedded, out flag, out flag2);
                        for (MimeNode mimeNode = headerList.FirstChild; mimeNode != null; mimeNode = mimeNode.NextSibling)
                        {
                            if (HeaderId.ContentTransferEncoding == (mimeNode as Header).HeaderId)
                            {
                                if (flag || this.embedded)
                                {
                                    this.encoder = null;
                                }
                                else if (flag2)
                                {
                                    stream.Write(EightToSevenBitConverter.CteQP, 0, EightToSevenBitConverter.CteQP.Length);
                                    this.encoder = new QPEncoder();
                                }
                                else
                                {
                                    stream.Write(EightToSevenBitConverter.CteBase64, 0, EightToSevenBitConverter.CteBase64.Length);
                                    this.encoder = new Base64Encoder();
                                }
                            }
                            else
                            {
                                mimeNode.WriteTo(stream);
                            }
                        }
                        stream.Write(MimeString.CrLf, 0, MimeString.CrLf.Length);
                        return(true);
                    }
                }
                return(false);
            }
Ejemplo n.º 29
0
        /// <summary>
        /// Get MIME encoded header item (if don't fit in ASCII symbols) with specific text and MIME encodings
        /// </summary>
        public string this[string name, Encoding encoding, ContentTransferEncoding mimeEncoding]
        {
            // use MIME encoding only if non-ascii symbols & quoted-printable or base64 mime encoding
            get
            {
                if (this[name] == null)
                {
                    return(null);
                }

                MatchEvaluator nonAsciiReplacer = match =>
                                                  mimeEncoding == ContentTransferEncoding.Unknown ? match.Value :
                                                  encoding.GetString(
                    Util.Encode(match.Value, encoding, mimeEncoding, true, false));

                return(headerFolding.Replace(nonAsciiReplace.Replace(this[name], nonAsciiReplacer),
                                             string.Format("$1{0}$2", Util.CRLF)));
            }
        }
Ejemplo n.º 30
0
        internal void SetBody(string value)
        {
            if (ContentTransferEncoding.Is("quoted-printable"))
            {
                value = Utilities.DecodeQuotedPrintable(value, Encoding);
            }
            else if (ContentTransferEncoding.Is("base64")
                     //only decode the content if it is a text document
                     && ContentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) &&
                     Utilities.IsValidBase64String(value))
            {
                var data = Convert.FromBase64String(value);
                using (var mem = new System.IO.MemoryStream(data))
                    using (var str = new System.IO.StreamReader(mem, Encoding))
                        value = str.ReadToEnd();

                ContentTransferEncoding = string.Empty;
            }

            Body = value;
        }
Ejemplo n.º 31
0
        private string ParseBody()
        {
            var body = String.Join(Environment.NewLine, _message
                                   // skip the headers
                                   .SkipWhile((x, i) => x.Trim().Length > 0 && i >= 0)
                                   // skip the blanks after the headers
                                   .SkipWhile((x, i) => x.Trim().Length == 0));

            if (!string.IsNullOrEmpty(Boundary))
            {
                ParseMime(body, Boundary);
                if (AlternateViews.Count > 0)
                {
                    var att = AlternateViews.FirstOrDefault(x => x.ContentType.Is("text/plain")) ??
                              AlternateViews.FirstOrDefault(x => x.ContentType.Contains("html"));

                    if (att != null)
                    {
                        return(att.Body);
                    }
                }
            }
            else
            {
                if (ContentTransferEncoding.Is("quoted-printable"))
                {
                    return(Utilities.DecodeQuotedPrintable(body, _encoding));
                }
                if (ContentTransferEncoding.Is("base64")
                    //only decode the content if it is a text document
                    && ContentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase))
                {
                    return(_encoding.GetString(Convert.FromBase64String(body)));
                }
                return(body);
            }
            return(String.Empty);
        }
Ejemplo n.º 32
0
 internal static string ParseContentTransferEncoding(ContentTransferEncoding encoding)
 {
     if (encoding == ContentTransferEncoding.Base64)
     {
         return("base64");
     }
     else if (encoding == ContentTransferEncoding.QuotedPrintable)
     {
         return("quoted-printable");
     }
     else if (encoding == ContentTransferEncoding.EightBit)
     {
         return("8bit");
     }
     else if (encoding == ContentTransferEncoding.Binary)
     {
         return("binary");
     }
     else
     {
         return("7bit");
     }
 }
Ejemplo n.º 33
0
 public void StartPart()
 {
     this.AssertOpen();
     switch (state) {
         case MimeWriteState.Complete:
         case MimeWriteState.PartContent:
             throw new System.InvalidOperationException(Resources.Strings.CannotStartPartHere);
         default:
             if (partDepth != 0) {
                 this.FlushHeader();
                 if (!currentPart.IsMultipart)
                     throw new System.InvalidOperationException(Resources.Strings.NonMultiPartPartsCannotHaveChildren);
                 if (!foundMimeVersion && forceMime && partDepth == 1)
                     this.WriteMimeVersion();
                 this.Write(MimeString.CrLf, 0, MimeString.CrLf.Length);
                 this.WriteBoundary(currentPart.Boundary, false);
             }
             var part = new PartData();
             this.PushPart(ref part);
             state = MimeWriteState.StartPart;
             contentWritten = false;
             contentTransferEncoding = ContentTransferEncoding.SevenBit;
             break;
     }
 }
Ejemplo n.º 34
0
 private void FlushHeader()
 {
     headerValueWritten = false;
     if (lastHeader == null)
         return;
     if (lastHeader.HeaderId == HeaderId.MimeVersion && partDepth == 1)
         foundMimeVersion = true;
     else if (lastHeader.HeaderId == HeaderId.ContentTransferEncoding) {
         var data = lastHeader.Value;
         if (data != null)
             contentTransferEncoding = MimePart.GetEncodingType(new MimeString(data));
     } else if (lastHeader.HeaderId == HeaderId.ContentType) {
         var contentTypeHeader = lastHeader as ContentTypeHeader;
         if (contentTypeHeader.IsMultipart) {
             currentPart.IsMultipart = true;
             currentPart.Boundary = contentTypeHeader["boundary"].RawValue;
         } else
             currentPart.IsMultipart = false;
         currentPart.HasContentType = true;
     }
     lastHeader.WriteTo(shimStream, encodingOptions);
     lastHeader = null;
 }
 private Stream GetContentStream(ContentTransferEncoding contentTransferEncoding, MultiAsyncResult multiResult)
 {
     this.CheckBoundary();
     this.bufferBuilder.Append(CRLF);
     this.Flush(multiResult);
     Stream stream = this.stream;
     if (contentTransferEncoding == ContentTransferEncoding.SevenBit)
     {
         stream = new SevenBitStream(stream);
     }
     else if (contentTransferEncoding == ContentTransferEncoding.QuotedPrintable)
     {
         stream = new QuotedPrintableStream(stream, this.lineLength);
     }
     else if (contentTransferEncoding == ContentTransferEncoding.Base64)
     {
         stream = new Base64Stream(stream, this.lineLength);
     }
     ClosableStream stream2 = new ClosableStream(stream, this.onCloseHandler);
     this.contentStream = stream2;
     return stream2;
 }
 internal Stream GetContentStream(ContentTransferEncoding contentTransferEncoding)
 {
     if (this.isInContent)
     {
         throw new InvalidOperationException(SR.GetString("MailWriterIsInContent"));
     }
     this.isInContent = true;
     return this.GetContentStream(contentTransferEncoding, null);
 }
Ejemplo n.º 37
0
 public EncodingDataStorage(Internal.DataStorage storage, long start, long end, ContentTransferEncoding cte)
     : base(storage, start, end, cte, true)
 {
 }
 /// <summary>
 /// Constructor that when given a stream, converts to encoded string based on encoding provided and saves it to content data
 /// </summary>
 /// <param name="stream"></param>
 /// <param name="encoding"></param>
 public FileContent(Stream stream, ContentTransferEncoding encoding)
     {
     this.Content = encoding == ContentTransferEncoding.Base64 ? System.Convert.ToBase64String(ReadStreamAsByteArray(stream)) : ReadStreamAsString(stream);
     this.ContentTransferEncoding = encoding;
     }
Ejemplo n.º 39
0
 internal EncodingEntry(byte[] name, ContentTransferEncoding type)
 {
     Name = name;
     Type = type;
 }
 /// <summary>
 /// Initializes a new instance of the Content class. To be used for string content.
 /// </summary>
 public FileContent(string content, ContentTransferEncoding contentTransferEncoding)
     {
     this.Content = content;
     this.ContentTransferEncoding = contentTransferEncoding;
     }
 public PartContentWriteStream(MimePart mimePart, ContentTransferEncoding contentTransferEncoding)
     : base(new Internal.TemporaryDataStorage())
 {
     _mimePart = mimePart;
     _contentTransferEncoding = contentTransferEncoding;
 }
Ejemplo n.º 42
0
 /// <summary>
 ///		Obtiene la descripción del tipo de transferencia
 /// </summary>
 internal static string GetTransferEncoding(ContentTransferEncoding intTransferEncoding)
 {
     switch (intTransferEncoding)
         { case ContentTransferEncoding.Base64:
                 return cnstStrTransferEncodingBase64;
             case ContentTransferEncoding.QuotedPrintable:
                 return cnstStrTransferEncodingQuotedPrintable;
             case ContentTransferEncoding.Bit7:
                 return cnstStrTransferEncoding7Bit;
             case ContentTransferEncoding.Bit8:
                 return cnstStrTransferEncoding8Bit;
             default:
                 return "";
         }
 }
Ejemplo n.º 43
0
 void ParseValue()
 {
     if (this.contentTransferEncodingValue == null)
     {
         int offset = 0;
         this.contentTransferEncodingValue = (Value.Length == 0) ? Value : ((Value[0] == '"') ? MailBnfHelper.ReadQuotedString(Value, ref offset, null) : MailBnfHelper.ReadToken(Value, ref offset, null));
         switch (this.contentTransferEncodingValue)
         {
             case "7bit":
                 this.contentTransferEncoding = ContentTransferEncoding.SevenBit;
                 break;
             case "8bit":
                 this.contentTransferEncoding = ContentTransferEncoding.EightBit;
                 break;
             case "binary":
                 this.contentTransferEncoding = ContentTransferEncoding.Binary;
                 break;
             default:
                 this.contentTransferEncoding = ContentTransferEncoding.Other;
                 break;
         }
     }
 }
Ejemplo n.º 44
0
 public CodingDataStorage(Internal.DataStorage storage, long start, long end, ContentTransferEncoding cte, bool encode)
 {
     storage.AddRef();
     this.storage = storage;
     this.start = start;
     this.end = end;
     this.cte = cte;
     this.encode = encode;
 }
Ejemplo n.º 45
0
 public ContentTransferEncodingHeader(ContentTransferEncoding contentTransferEncoding, string value)
     : base("content-transfer-encoding", null)
 {
     this.contentTransferEncoding = contentTransferEncoding;
     this.contentTransferEncodingValue = value;
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="stream"></param>
 /// <param name="encoding"></param>
 public File(Stream stream, ContentTransferEncoding encoding)
     : base(stream, encoding)
 {
 }
 internal Stream GetContentStream(ContentTransferEncoding contentTransferEncoding)
 {
     return this.GetContentStream(contentTransferEncoding, null);
 }
Ejemplo n.º 48
0
 public ContentPositionEntry(long contentStart, long headersEnd, ContentTransferEncoding contentTransferEncoding)
 {
     ContentStart = contentStart;
     HeadersEnd = headersEnd;
     ContentTransferEncoding = contentTransferEncoding;
 }
Ejemplo n.º 49
0
 public void Reset(bool cleanMimeState)
 {
     this.StreamMode = false;
     this.ContentType = MajorContentType.Other;
     Epilogue = false;
     this.TransferEncoding = ContentTransferEncoding.SevenBit;
     if (cleanMimeState)
         this.IsMime = false;
     boundaryValue = new MimeString();
     boundaryCrc = 0U;
     endBoundaryCrc = 0U;
     this.PartDepth = 0;
 }
Ejemplo n.º 50
0
		/// <summary>
		/// Decodes a byte array into another byte array based upon the Content Transfer encoding
		/// </summary>
		/// <param name="messageBody">The byte array to decode into another byte array</param>
		/// <param name="contentTransferEncoding">The <see cref="ContentTransferEncoding"/> of the byte array</param>
		/// <returns>A byte array which comes from the <paramref name="contentTransferEncoding"/> being used on the <paramref name="messageBody"/></returns>
		/// <exception cref="ArgumentNullException">If <paramref name="messageBody"/> is <see langword="null"/></exception>
		/// <exception cref="ArgumentOutOfRangeException">Thrown if the <paramref name="contentTransferEncoding"/> is unsupported</exception>
		private static byte[] DecodeBody(byte[] messageBody, ContentTransferEncoding contentTransferEncoding)
		{
			if (messageBody == null)
				throw new ArgumentNullException("messageBody");

			switch (contentTransferEncoding)
			{
				case ContentTransferEncoding.QuotedPrintable:
					// If encoded in QuotedPrintable, everything in the body is in US-ASCII
					return QuotedPrintable.DecodeContentTransferEncoding(Encoding.ASCII.GetString(messageBody));

				case ContentTransferEncoding.Base64:
					// If encoded in Base64, everything in the body is in US-ASCII
					return Base64.Decode(Encoding.ASCII.GetString(messageBody));

				case ContentTransferEncoding.SevenBit:
				case ContentTransferEncoding.Binary:
				case ContentTransferEncoding.EightBit:
					// We do not have to do anything
					return messageBody;

				default:
					throw new ArgumentOutOfRangeException("contentTransferEncoding");
			}
		}
Ejemplo n.º 51
0
 internal static Schema.Mime.Encoders.ByteEncoder CreateEncoder(ContentTransferEncoding encoding)
 {
     switch (encoding) {
         case ContentTransferEncoding.QuotedPrintable:
             return new Schema.Mime.Encoders.QPEncoder();
         case ContentTransferEncoding.Base64:
             return new Schema.Mime.Encoders.Base64Encoder();
         case ContentTransferEncoding.UUEncode:
             return new Schema.Mime.Encoders.UUEncoder();
         default:
             return null;
     }
 }
Ejemplo n.º 52
0
 public void SetTransferEncoding(ContentTransferEncoding encoding)
 {
     currentLevel.TransferEncoding = encoding;
 }
 private Stream GetContentStream(ContentTransferEncoding contentTransferEncoding, MultiAsyncResult multiResult)
 {
     if (this.isInContent)
     {
         throw new InvalidOperationException(SR.GetString("MailWriterIsInContent"));
     }
     this.isInContent = true;
     this.bufferBuilder.Append(CRLF);
     this.Flush(multiResult);
     Stream stream = this.stream;
     if (contentTransferEncoding == ContentTransferEncoding.SevenBit)
     {
         stream = new SevenBitStream(stream);
     }
     else if (contentTransferEncoding == ContentTransferEncoding.QuotedPrintable)
     {
         stream = new QuotedPrintableStream(stream, this.lineLength);
     }
     else if (contentTransferEncoding == ContentTransferEncoding.Base64)
     {
         stream = new Base64Stream(stream, this.lineLength);
     }
     ClosableStream stream2 = new ClosableStream(stream, this.onCloseHandler);
     this.contentStream = stream2;
     return stream2;
 }