Example #1
0
        public void TestWriteTo(string text)
        {
            var builder = new BodyBuilder();

            builder.Attachments.Add("filename", new MemoryStream(Encoding.UTF8.GetBytes(text)));
            builder.TextBody = "This is the text body.";

            var body = builder.ToMessageBody();

            using (var stream = new MemoryStream()) {
                var options = FormatOptions.Default.Clone();
                options.NewLineFormat = NewLineFormat.Dos;

                body.WriteTo(options, stream);
                stream.Position = 0;

                var multipart = (Multipart)MimeEntity.Load(stream);
                using (var input = ((MimePart)multipart[1]).Content.Open()) {
                    var buffer = new byte[1024];
                    int n;

                    n = input.Read(buffer, 0, buffer.Length);

                    var content = Encoding.UTF8.GetString(buffer, 0, n);

                    Assert.AreEqual(text, content);
                }
            }
        }
Example #2
0
        /// <summary>
        /// Decrypt the specified encryptedData.
        /// </summary>
        /// <remarks>
        /// Decrypts the specified encryptedData.
        /// </remarks>
        /// <returns>The decrypted <see cref="MimeKit.MimeEntity"/>.</returns>
        /// <param name="encryptedData">The encrypted data.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="encryptedData"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="Org.BouncyCastle.Cms.CmsException">
        /// An error occurred in the cryptographic message syntax subsystem.
        /// </exception>
        /// <exception cref="System.OperationCanceledException">
        /// The operation was cancelled via the cancellation token.
        /// </exception>
        public override MimeEntity Decrypt(Stream encryptedData, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (encryptedData == null)
            {
                throw new ArgumentNullException(nameof(encryptedData));
            }

            var parser     = new CmsEnvelopedDataParser(encryptedData);
            var recipients = parser.GetRecipientInfos();
            var algorithm  = parser.EncryptionAlgorithmID;
            AsymmetricKeyParameter key;

            foreach (RecipientInformation recipient in recipients.GetRecipients())
            {
                if ((key = GetPrivateKey(recipient.RecipientID)) == null)
                {
                    continue;
                }

                var content = recipient.GetContent(key);
                var memory  = new MemoryStream(content, false);

                return(MimeEntity.Load(memory, true, cancellationToken));
            }

            throw new CmsException("A suitable private key could not be found for decrypting.");
        }
Example #3
0
        public static void p5_mime_load_file(ApplicationContext context, ActiveEventArgs e)
        {
            // Making sure we clean up after ourselves
            using (new ArgsRemover(e.Args, true)) {
                // Keeping base folder to application around
                string baseFolder = Common.GetRootFolder(context).TrimEnd('/');

                // Looping through each filename supplied by caller
                foreach (var idxFilename in XUtil.Iterate <string> (context, e.Args))
                {
                    // Verifying user is authorized to reading from currently iterated file
                    context.RaiseEvent(".p5.io.authorize.read-file", new Node("", idxFilename).Add("args", e.Args));

                    // Loading, processing and returning currently iterated message
                    var parser = new helpers.MimeParser(
                        context,
                        e.Args,
                        MimeEntity.Load(baseFolder + idxFilename),
                        e.Args.GetExChildValue <string> ("attachment-folder", context));

                    // Parses the MimeEntity and stuffs results into e.Args node
                    parser.Process();
                }
            }
        }
        internal static MimeMessage CreateTestMimeMessage(out ExpectedEmailValues expectedEmailValues)
        {
            var fromEmailAddresses = new List <string> {
                "*****@*****.**", "*****@*****.**"
            };

            var toEmailAddresses = new List <string> {
                "*****@*****.**", "*****@*****.**"
            };

            var from     = fromEmailAddresses.Select(adr => new MailboxAddress(adr)).ToList();
            var to       = toEmailAddresses.Select(adr => new MailboxAddress(adr)).ToList();
            var bodyText = CreateBodyText();

            const string Subject = "Subject1234";

            using (var ms = new MemoryStream())
                using (var sw = new StreamWriter(ms))
                {
                    sw.Write(bodyText);
                    sw.Flush();
                    ms.Seek(0, SeekOrigin.Begin);

                    var body        = MimeEntity.Load(ms);
                    var mimeMessage = new MimeMessage(from, to, Subject, body);

                    expectedEmailValues = new ExpectedEmailValues(fromEmailAddresses, toEmailAddresses, Subject, bodyText);
                    return(mimeMessage);
                }
        }
Example #5
0
        public As4Message Send(Uri uri, As4Message message)
        {
            var mimeMessage = As4MessageToMimeEntity.Serialize(message);

            var request = (HttpWebRequest)WebRequest.Create(uri);

            request.Method      = "POST";
            request.ContentType = mimeMessage.ContentType.MimeType + mimeMessage.ContentType.Parameters;

            if (Certificate != null)
            {
                request.ClientCertificates.Add(Certificate);
            }

            using (Stream requestStream = request.GetRequestStream())
            {
                mimeMessage.WriteTo(requestStream, true);
            }

            var response = (HttpWebResponse)request.GetResponse();

            if (string.IsNullOrEmpty(response.ContentType))
            {
                return(null);
            }

            var contentType = ContentType.Parse(response.ContentType);

            using (Stream responseStream = response.GetResponseStream())
            {
                var mimeEntity = MimeEntity.Load(contentType, responseStream);
                return(MimeEntityToAs4Message.Deserialize(mimeEntity));
            }
        }
Example #6
0
        public virtual void TestSecureMimeEncryption()
        {
            var certificate = new X509Certificate2(Path.Combine("..", "..", "TestData", "smime", "smime.p12"), "no.secret");
            var body        = new TextPart("plain")
            {
                Text = "This is some cleartext that we'll end up encrypting..."
            };
            var recipients = new CmsRecipientCollection();

            recipients.Add(new CmsRecipient(certificate, SubjectIdentifierType.SubjectKeyIdentifier));

            using (var ctx = CreateContext()) {
                var encrypted = ApplicationPkcs7Mime.Encrypt(ctx, recipients, body);

                Assert.AreEqual(SecureMimeType.EnvelopedData, encrypted.SecureMimeType, "S/MIME type did not match.");

                using (var stream = new MemoryStream()) {
                    ctx.DecryptTo(encrypted.ContentObject.Open(), stream);
                    stream.Position = 0;

                    var decrypted = MimeEntity.Load(stream);

                    Assert.IsInstanceOf <TextPart> (decrypted, "Decrypted part is not the expected type.");
                    Assert.AreEqual(body.Text, ((TextPart)decrypted).Text, "Decrypted content is not the same as the original.");
                }
            }
        }
Example #7
0
        private static As4Message Read(IOwinRequest request)
        {
            var contentType = ContentType.Parse(request.ContentType);
            var requestMime = MimeEntity.Load(contentType, request.Body);

            return(MimeEntityToAs4Message.Deserialize(requestMime));
        }
Example #8
0
        /*
         * Parses results, and puts into args
         */
        private static void ParseResponse(
            ApplicationContext context,
            Node args,
            Node result,
            Node decryptionKeys,
            Node attachmentFolder)
        {
            // Retrieving response
            HttpWebResponse response = result ["response-native"].UnTie().Value as HttpWebResponse;

            // Retrieving MimeEntity from stream
            using (Stream responseStream = response.GetResponseStream()) {
                MimeEntity entity = MimeEntity.Load(
                    ContentType.Parse(response.ContentType),
                    responseStream);

                // Moving entire result into args
                args.Add(result);

                // Raising Active Event that will parse MIME content
                var oldValue = result.Value;
                result.Value = entity;
                try {
                    result.Add(decryptionKeys);
                    result.Add(attachmentFolder);
                    context.RaiseEvent(".p5.mime.parse-native", result);
                } finally {
                    result.Value = oldValue;
                }
            }
        }
        private static async Task <Multipart> ReadMultipartAsync(HttpContent content, CancellationToken ct)
        {
            var responseStream = await content
                                 .ReadAsStreamAsync();

            var headerStream = new MemoryStream();

            using (var headerWriter = new StreamWriter(headerStream, new UTF8Encoding(false), 1000, true)
            {
                NewLine = "\r\n",
            })
            {
                foreach (var contentHeader in content.Headers)
                {
                    var line = $"{contentHeader.Key}: {string.Join(", ", contentHeader.Value)}";
                    await headerWriter.WriteLineAsync(line);
                }

                await headerWriter.WriteLineAsync();
            }

            headerStream.Position = 0;

            using (var input = new ChainedStream())
            {
                input.Add(headerStream);
                input.Add(responseStream, true);

                var multipart = MimeEntity.Load(input, ct);
                return(Assert.IsType <Multipart>(multipart));
            }
        }
Example #10
0
        public static void _p5_mime_load_from_stream(ApplicationContext context, ActiveEventArgs e)
        {
            // Making sure we clean up after ourselves.
            using (new ArgsRemover(e.Args, true)) {
                // Sanity check.
                var stream = e.Args.Value as Stream;
                if (e.Args.Value == null)
                {
                    throw new LambdaException(
                              "No stream provided to [.p5.mime.parse-from-stream]",
                              e.Args,
                              context);
                }

                // Loading MimeEntity from specified stream.
                MimeEntity entity = null;
                if (e.Args ["Content-Type"] != null)
                {
                    entity = MimeEntity.Load(ContentType.Parse(e.Args ["Content-Type"].Get <string> (context)), stream);
                }
                else
                {
                    entity = MimeEntity.Load(stream);
                }
                var parser = new helpers.MimeParser(
                    context,
                    e.Args,
                    entity,
                    e.Args.GetExChildValue <string> ("attachment-folder", context),
                    e.Args.GetExChildValue <bool> ("attachment-folder-no-prefix", context, true));

                // Parses the MimeEntity and stuffs results into e.Args node
                parser.Process();
            }
        }
Example #11
0
        public static MimeMessage MultipartMimeMessage(byte[] dataSource) // throws MessagingException
        {
            Multipart   mimeMultipart = MimeEntity.Load(ParserOptions.Default, dataSource.ToStream(), false) as Multipart;
            MimeMessage m             = new MimeMessage();

            m.Body = mimeMultipart;
            return(m);
        }
Example #12
0
 /// <summary>
 /// Implementation of your slot.
 /// </summary>
 /// <param name="signaler">Signaler that raised the signal.</param>
 /// <param name="input">Arguments to your slot.</param>
 public void Signal(ISignaler signaler, Node input)
 {
     using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(input.GetEx <string>())))
     {
         using (var entity = MimeEntity.Load(stream))
         {
             helpers.MimeParser.Parse(input, entity);
         }
     }
 }
Example #13
0
 public static void p5_web_request_parse_mime(ApplicationContext context, ActiveEventArgs e)
 {
     // Making sure we clean up after ourselves
     using (new Utilities.ArgsRemover(e.Args, true)) {
         // Loading MimeEntity from request stream
         var entity = MimeEntity.Load(
             ContentType.Parse(HttpContext.Current.Request.ContentType),
             HttpContext.Current.Request.InputStream);
         e.Args.Value = entity;
         context.Raise(".p5.mime.parse-native", e.Args);
     }
 }
Example #14
0
        /// <summary>
        /// Decompress the specified stream.
        /// </summary>
        /// <remarks>
        /// Decompress the specified stream.
        /// </remarks>
        /// <returns>The decompressed mime part.</returns>
        /// <param name="stream">The stream to decompress.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="stream"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="Org.BouncyCastle.Cms.CmsException">
        /// An error occurred in the cryptographic message syntax subsystem.
        /// </exception>
        public MimeEntity Decompress(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            var parser  = new CmsCompressedDataParser(stream);
            var content = parser.GetContent();

            return(MimeEntity.Load(content.ContentStream));
        }
        public static void p5_mime_parse(ApplicationContext context, ActiveEventArgs e)
        {
            // House cleaning.
            using (new ArgsRemover(e.Args, true)) {
                // Looping through each MIME message supplied.
                foreach (var idxMimeMessage in XUtil.Iterate <string> (context, e.Args))
                {
                    // Sanity check.
                    if (string.IsNullOrEmpty(idxMimeMessage))
                    {
                        throw new LambdaException(
                                  "No MIME message provided to [p5.mime.parse]",
                                  e.Args,
                                  context);
                    }

                    // Loading MIME entity from stream.
                    using (var writer = new StreamWriter(new MemoryStream())) {
                        // Writing MIME content to StreamWriter, flushing the stream, and setting stream's read head back to beginning.
                        writer.Write(idxMimeMessage);
                        writer.Flush();
                        writer.BaseStream.Position = 0;

                        // Creating the MIME entity to hold our parsed content.
                        MimeEntity entity = null;

                        // Checking if an explicit [Content-Type] was supplied.
                        if (e.Args ["Content-Type"] != null)
                        {
                            entity = MimeEntity.Load(ContentType.Parse(e.Args ["Content-Type"].GetExValue <string> (context)), writer.BaseStream);
                        }
                        else
                        {
                            entity = MimeEntity.Load(writer.BaseStream);
                        }

                        // Creating our parser wrapper.
                        var parser = new helpers.MimeParser(
                            context,
                            e.Args,
                            entity,
                            e.Args.GetExChildValue <string> ("attachment-folder", context),
                            e.Args.GetExChildValue <bool> ("attachments-use-prefix", context, true));

                        // Parses the MimeEntity and stuffs results into e.Args node.
                        parser.Process();
                    }
                }
            }
        }
        public static void p5_mime_load(ApplicationContext context, ActiveEventArgs e)
        {
            // House cleaning.
            using (new ArgsRemover(e.Args, true)) {
                // Looping through each file supplied by caller.
                foreach (var idxMimeMessage in XUtil.Iterate <string> (context, e.Args))
                {
                    // Sanity check.
                    if (string.IsNullOrEmpty(idxMimeMessage))
                    {
                        throw new LambdaException(
                                  "No file supplied to [p5.mime.load]",
                                  e.Args,
                                  context);
                    }

                    // Retrieving output filename, unrolling path, and authorising that user has read access to file.
                    var filePath = idxMimeMessage;
                    filePath = context.RaiseEvent(".p5.io.unroll-path", new Node("", filePath)).Get <string> (context);
                    context.RaiseEvent(".p5.io.authorize.read-file", new Node("", filePath).Add("args", e.Args));

                    // Creating a FileStream wrapping our file.
                    using (var reader = File.OpenRead(Common.GetRootFolder(context) + filePath)) {
                        // Creating our MIME entity.
                        MimeEntity entity = null;

                        // Checking if caller supplied an explicit [Content-Type].
                        if (e.Args ["Content-Type"] != null)
                        {
                            entity = MimeEntity.Load(ContentType.Parse(e.Args ["Content-Type"].GetExValue <string> (context)), reader);
                        }
                        else
                        {
                            entity = MimeEntity.Load(reader);
                        }

                        // Creating our MIME parser.
                        var parser = new helpers.MimeParser(
                            context,
                            e.Args,
                            entity,
                            e.Args.GetExChildValue <string> ("attachment-folder", context),
                            e.Args.GetExChildValue <bool> ("attachments-use-prefix", context, true));

                        // Parses the MimeEntity and stuffs the results into e.Args node.
                        parser.Process();
                    }
                }
            }
        }
Example #17
0
        private void CheckSerialization(Envelope envelope, params Attachment[] attachments)
        {
            var message     = Messages.Create(envelope, attachments);
            var mimeEntity  = As4MessageToMimeEntity.Serialize(message);
            var contentType = mimeEntity.ContentType;
            var stream      = new MemoryStream();

            mimeEntity.WriteTo(stream, true);
            stream.Position = 0;
            var decodedEntity  = MimeEntity.Load(contentType, stream);
            var decodedMessage = MimeEntityToAs4Message.Deserialize(decodedEntity);

            MessageAssert.AreEqual(message, decodedMessage);
        }
Example #18
0
        public void TestLoadHttpWebResponse()
        {
            var text        = "This is some text and stuff." + Environment.NewLine;
            var contentType = new ContentType("text", "plain");

            using (var content = new MemoryStream(Encoding.ASCII.GetBytes(text), false)) {
                var entity = MimeEntity.Load(contentType, content);

                Assert.IsInstanceOf <TextPart> (entity);

                var part = (TextPart)entity;

                Assert.AreEqual(text, part.Text);
            }
        }
Example #19
0
		/// <summary>
		/// Decrypt the encrypted data.
		/// </summary>
		/// <remarks>
		/// Decrypt the encrypted data.
		/// </remarks>
		/// <returns>The decrypted <see cref="MimeKit.MimeEntity"/>.</returns>
		/// <param name="encryptedData">The encrypted data.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <paramref name="encryptedData"/> is <c>null</c>.
		/// </exception>
		/// <exception cref="System.Security.Cryptography.CryptographicException">
		/// An error occurred in the cryptographic message syntax subsystem.
		/// </exception>
		public override MimeEntity Decrypt (Stream encryptedData)
		{
			if (encryptedData == null)
				throw new ArgumentNullException ("encryptedData");

			var enveloped = new EnvelopedCms ();

			enveloped.Decode (ReadAllBytes (encryptedData));
			enveloped.Decrypt ();

			var decryptedData = enveloped.Encode ();

			var memory = new MemoryStream (decryptedData, false);

			return MimeEntity.Load (memory, true);
		}
Example #20
0
 /// <summary>
 /// Implementation of your slot.
 /// </summary>
 /// <param name="signaler">Signaler that raised the signal.</param>
 /// <param name="input">Arguments to your slot.</param>
 public void Signal(ISignaler signaler, Node input)
 {
     try
     {
         using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(input.GetEx <string>())))
         {
             var message = MimeEntity.Load(stream);
             helpers.MimeParser.Parse(input, message);
             input.Value = null;
         }
     }
     finally
     {
         input.Children.FirstOrDefault(x => x.Name == "key")?.UnTie();
     }
 }
        public void TestDocumentRootByType()
        {
            var related = (MultipartRelated)MimeEntity.Load(Path.Combine(TestHelper.ProjectDir, "TestData", "messages", "multipart-related-mhtml.txt"));

            Assert.AreEqual(2, related.Count, "Count");

            var image = related[0];

            Assert.AreEqual("image/png", image.ContentType.MimeType, "related[0]");

            var html = related[1];

            Assert.AreEqual("text/html", html.ContentType.MimeType, "related[1]");

            Assert.AreEqual(html, related.Root, "Root");
        }
        public static void _p5_mime_load_from_stream(ApplicationContext context, ActiveEventArgs e)
        {
            // House cleaning.
            using (new ArgsRemover(e.Args, true)) {
                // Sanity check.
                var tuple = e.Args.Value as Tuple <object, Stream>;
                if (tuple == null)
                {
                    throw new LambdaException(
                              "No Tuple<object, Stream> provided to [.p5.mime.load-from-stream]",
                              e.Args,
                              context);
                }
                var stream = tuple.Item2;
                if (stream == null)
                {
                    throw new LambdaException(
                              "No stream provided to [.p5.mime.load-from-stream]",
                              e.Args,
                              context);
                }

                // Creating our MIME entity.
                MimeEntity entity = null;

                // Checking if caller supplied an explicit [Content-Type].
                if (e.Args ["Content-Type"] != null)
                {
                    entity = MimeEntity.Load(ContentType.Parse(e.Args ["Content-Type"].Get <string> (context)), stream);
                }
                else
                {
                    entity = MimeEntity.Load(stream);
                }

                // Creating our parser.
                var parser = new helpers.MimeParser(
                    context,
                    e.Args,
                    entity,
                    e.Args.GetExChildValue <string> ("attachment-folder", context),
                    e.Args.GetExChildValue <bool> ("attachments-use-prefix", context, true));

                // Parses the MimeEntity and stuffs the results into e.Args node.
                parser.Process();
            }
        }
Example #23
0
 /// <summary>
 /// Creates a MimeMultipart MIME message from an input stream, which does not contain the header "Content-Type:".
 /// Thus the mime type must be supplied as an argument.
 /// </summary>
 /// <param name="contents"></param>
 /// <param name="mimeType"></param>
 /// <returns></returns>
 public static Multipart ParseMultipart(Stream contents, string mimeType)
 {
     try
     {
         var ct      = ContentType.Parse(mimeType);
         var message = MimeEntity.Load(ct, contents);
         return(message as Multipart);
     }
     catch (IOException e)
     {
         throw new ArgumentException("Unable to create ByteArrayDataSource; " + e.Message, e);
     }
     catch (Exception e)
     {
         throw new ArgumentException("Unable to create Multipart mime message; " + e.Message, e);
     }
 }
Example #24
0
        public static void p5_mime_load(ApplicationContext context, ActiveEventArgs e)
        {
            // Making sure we clean up after ourselves
            using (new ArgsRemover(e.Args, true)) {
                // Looping through each MIME message supplied
                foreach (var idxMimeMessage in XUtil.Iterate <string> (context, e.Args))
                {
                    // Sanity check
                    if (string.IsNullOrEmpty(idxMimeMessage))
                    {
                        throw new LambdaException(
                                  "No MIME message provided to [p5.mime.parse]",
                                  e.Args,
                                  context);
                    }

                    // Retrieving output filename, and doing some basic sanity checking.
                    var filePath = idxMimeMessage;
                    filePath = context.RaiseEvent(".p5.io.unroll-path", new Node("", filePath)).Get <string> (context);
                    context.RaiseEvent(".p5.io.authorize.read-file", new Node("", filePath).Add("args", e.Args));

                    // Loading MIME entity from currentl iterated file.
                    using (var reader = File.OpenRead(Common.GetRootFolder(context) + filePath)) {
                        // Loading MimeEntity from MemoryStream
                        MimeEntity entity = null;
                        if (e.Args ["Content-Type"] != null)
                        {
                            entity = MimeEntity.Load(ContentType.Parse(e.Args ["Content-Type"].Get <string> (context)), reader);
                        }
                        else
                        {
                            entity = MimeEntity.Load(reader);
                        }
                        var parser = new helpers.MimeParser(
                            context,
                            e.Args,
                            entity,
                            e.Args.GetExChildValue <string> ("attachment-folder", context),
                            e.Args.GetExChildValue <bool> ("attachment-folder-no-prefix", context, true));

                        // Parses the MimeEntity and stuffs results into e.Args node
                        parser.Process();
                    }
                }
            }
        }
Example #25
0
        public static void p5_mime_parse(ApplicationContext context, ActiveEventArgs e)
        {
            // Making sure we clean up after ourselves
            using (new ArgsRemover(e.Args, true)) {
                // Looping through each MIME message supplied
                foreach (var idxMimeMessage in XUtil.Iterate <string> (context, e.Args))
                {
                    // Sanity check
                    if (string.IsNullOrEmpty(idxMimeMessage))
                    {
                        throw new LambdaException(
                                  "No MIME message provided to [p5.mime.parse]",
                                  e.Args,
                                  context);
                    }

                    // Loading MIME entity from stream
                    using (var writer = new StreamWriter(new MemoryStream())) {
                        // Writing MIME content to StreamWriter, flushing the stream, and setting reader head back to beginning
                        writer.Write(idxMimeMessage);
                        writer.Flush();
                        writer.BaseStream.Position = 0;

                        // Loading MimeEntity from MemoryStream
                        MimeEntity entity = null;
                        if (e.Args["Content-Type"] != null)
                        {
                            entity = MimeEntity.Load(ContentType.Parse(e.Args["Content-Type"].Get <string> (context)), writer.BaseStream);
                        }
                        else
                        {
                            entity = MimeEntity.Load(writer.BaseStream);
                        }
                        var parser = new helpers.MimeParser(
                            context,
                            e.Args,
                            entity,
                            e.Args.GetExChildValue <string> ("attachment-folder", context));

                        // Parses the MimeEntity and stuffs results into e.Args node
                        parser.Process();
                    }
                }
            }
        }
Example #26
0
        public void TestArgumentExceptions()
        {
            var part = new MimePart();

            Assert.Throws <ArgumentNullException> (() => new MimePart((string)null));
            Assert.Throws <ArgumentNullException> (() => new MimePart((ContentType)null));
            Assert.Throws <ArgumentNullException> (() => new MimePart(null, "octet-stream"));
            Assert.Throws <ArgumentNullException> (() => new MimePart("application", null));

            Assert.Throws <ArgumentOutOfRangeException> (() => part.ContentDuration = -1);
            Assert.Throws <ArgumentOutOfRangeException> (() => part.Prepare(EncodingConstraint.SevenBit, 1));

            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load((Stream)null));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load((Stream)null, true));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load((ParserOptions)null, Stream.Null));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load(ParserOptions.Default, (Stream)null));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load(null, Stream.Null, true));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load(ParserOptions.Default, (Stream)null, true));

            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load((ContentType)null, Stream.Null));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load(new ContentType("application", "octet-stream"), null));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load(null, new ContentType("application", "octet-stream"), Stream.Null));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load(ParserOptions.Default, null, Stream.Null));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load(ParserOptions.Default, new ContentType("application", "octet-stream"), null));

            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load((string)null));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load(null, "fileName"));
            Assert.Throws <ArgumentNullException> (() => MimeEntity.Load(ParserOptions.Default, (string)null));

            Assert.Throws <ArgumentNullException> (() => part.Accept(null));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo((string)null));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo((Stream)null));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo((string)null, false));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo((Stream)null, false));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo(null, Stream.Null));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo(FormatOptions.Default, (Stream)null));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo(null, "fileName"));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo(FormatOptions.Default, (string)null));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo(null, Stream.Null, false));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo(FormatOptions.Default, (Stream)null, false));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo(null, "fileName", false));
            Assert.Throws <ArgumentNullException> (() => part.WriteTo(FormatOptions.Default, (string)null, false));
        }
Example #27
0
        public void TestTranscoding()
        {
            var path     = Path.Combine("..", "..", "TestData", "images", "girl.jpg");
            var expected = File.ReadAllBytes(path);

            var part = new MimePart("image", "jpeg")
            {
                Content = new MimeContent(new MemoryStream(expected, false)),
                ContentTransferEncoding = ContentEncoding.Base64,
                FileName = "girl.jpg"
            };

            // encode in base64
            using (var output = new MemoryStream()) {
                part.WriteTo(output);
                output.Position = 0;

                part = (MimePart)MimeEntity.Load(output);
            }

            // transcode to uuencode
            part.ContentTransferEncoding = ContentEncoding.UUEncode;
            using (var output = new MemoryStream()) {
                part.WriteTo(output);
                output.Position = 0;

                part = (MimePart)MimeEntity.Load(output);
            }

            // verify decoded content
            using (var output = new MemoryStream()) {
                part.Content.DecodeTo(output);
                output.Position = 0;

                var actual = output.ToArray();

                Assert.AreEqual(expected.Length, actual.Length);
                for (int i = 0; i < expected.Length; i++)
                {
                    Assert.AreEqual(expected[i], actual[i], "Image content differs at index {0}", i);
                }
            }
        }
                public override void Transform(Attachment attachment, Stream decryptedData, string contentType)
                {
                    // The decrypted data can contain MIME headers, therefore we'll need to parse
                    // the decrypted data as a MimePart, and make sure that the content is set correctly
                    // in the attachment.
                    var part = MimeEntity.Load(decryptedData) as MimePart;

                    if (part == null)
                    {
                        throw new InvalidOperationException("The decrypted stream could not be converted to a MIME part");
                    }

                    attachment.Content.Dispose();
                    attachment.UpdateContent(part.ContentObject.Stream, contentType);

                    foreach (Header header in part.Headers)
                    {
                        attachment.Properties.Add(header.Field, header.Value);
                    }
                }
        public void TestParsingOfCustomType()
        {
            var options = ParserOptions.Default.Clone();

            options.RegisterMimeType("text/html", typeof(CustomTextHtmlPart));

            using (var stream = new MemoryStream()) {
                var text = new TextPart("html")
                {
                    Text = "<html>this is some html and stuff</html>"
                };

                text.WriteTo(stream);
                stream.Position = 0;

                var html = MimeEntity.Load(options, stream);

                Assert.IsInstanceOf <CustomTextHtmlPart> (html, "Expected the text/html part to use our custom type.");
            }
        }
Example #30
0
        public void TestChainedHeadersAndContent()
        {
            var buf     = Encoding.ASCII.GetBytes("Content-Type: text/plain\r\n\r\n");
            var headers = new MemoryStream();
            var content = new MemoryStream();

            headers.Write(buf, 0, buf.Length);
            headers.Position = 0;

            buf = Encoding.ASCII.GetBytes("Hello, world!\r\n");

            content.Write(buf, 0, buf.Length);
            content.Position = 0;

            using (var chained = new ChainedStream()) {
                chained.Add(headers);
                chained.Add(content);

                var entity = MimeEntity.Load(chained, true) as TextPart;

                Assert.AreEqual("Hello, world!" + Environment.NewLine, entity.Text);
            }
        }