A leaf-node MIME part that contains content such as the message body text or an attachment.
A leaf-node MIME part that contains content such as the message body text or an attachment.
Inheritance: MimeKit.MimeEntity
示例#1
4
		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));
		}
示例#2
0
        /// <summary>
        /// Download all attachments (regular and embedded) to a local directory
        ///
        /// </summary>
        /// <param name="message"></param>
        private void DownloadAttachments(MimeMessage message)
        {
            if (message.BodyParts.Count() > 0)
            {
                foreach (MimeEntity attachment in message.BodyParts)
                {
                    string attachmentFile     = attachment.ContentDisposition?.FileName ?? attachment.ContentType.Name;
                    string attachmentFilePath = String.Concat(STORAGE.MimeKitAttachmentsDirectoryWork,
                                                              Path.GetFileName(attachmentFile));

                    if (!string.IsNullOrWhiteSpace(attachmentFile))
                    {
                        if (File.Exists(attachmentFilePath))
                        {
                            string extension = Path.GetExtension(attachmentFilePath);
                            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(attachmentFilePath);
                            attachmentFile = string.Format(fileNameWithoutExtension + "-{0}" + "{1}",
                                                           ++_duplicateFileCount, extension);
                            attachmentFilePath = Path.Combine(STORAGE.MimeKitAttachmentsDirectoryWork,
                                                              attachmentFile);
                        }

                        using (FileStream attachmentStream = File.Create(attachmentFilePath))
                        {
                            MimeKit.MimePart part = (MimeKit.MimePart)attachment;
                            part.ContentObject.DecodeTo(attachmentStream);
                        }

                        Console.WriteLine("Downloaded: " + attachmentFile);
                    }
                }
                _duplicateFileCount = 0;
            }
        }
示例#3
0
			string GetDataUri (MimePart attachment)
			{
				using (var memory = new MemoryStream ()) {
					attachment.ContentObject.DecodeTo (memory);
					var buffer = memory.GetBuffer ();
					var length = (int) memory.Length;
					var base64 = Convert.ToBase64String (buffer, 0, length);

					return string.Format ("data:{0};base64,{1}", attachment.ContentType.MimeType, base64);
				}
			}
示例#4
0
 /// <summary>
 /// 附件写入文件
 /// </summary>
 /// <param name="part"></param>
 /// <param name="filePath"></param>
 /// <returns></returns>
 private static void MimePartToFile(MimeKit.MimePart part, string filePath)
 {
     using (var ms = new MemoryStream())
     {
         part.ContentObject.DecodeTo(ms);
         ms.Position = 0;
         var ws = File.Create(filePath);
         ms.WriteTo(ws);
         ws.Flush();
         ws.Close();
     }
 }
        MimeEntity CreateAttachment(ContentType contentType, string path, Stream stream)
        {
            var        fileName = GetFileName(path);
            MimeEntity attachment;

            if (contentType.IsMimeType("message", "rfc822"))
            {
                var message = MimeMessage.Load(stream);
                var rfc822  = new MessagePart {
                    Message = message
                };

                rfc822.ContentDisposition          = new ContentDisposition(linked ? ContentDisposition.Inline : ContentDisposition.Attachment);
                rfc822.ContentDisposition.FileName = fileName;
                rfc822.ContentType.Name            = fileName;

                attachment = rfc822;
            }
            else
            {
                MimePart part;

                if (contentType.IsMimeType("text", "*"))
                {
                    // TODO: should we try to auto-detect charsets if no charset parameter is specified?
                    part = new TextPart(contentType);
                }
                else
                {
                    part = new MimePart(contentType);
                }

                part.IsAttachment = !linked;
                part.FileName     = fileName;

                LoadContent(part, stream);
                attachment = part;
            }

            if (linked)
            {
                attachment.ContentLocation = new Uri(fileName, UriKind.Relative);
            }

            return(attachment);
        }
示例#6
0
        async Task ConstructMimePartAsync(MimePart part, CancellationToken cancellationToken)
        {
            long endOffset, beginOffset = GetOffset(inputIndex);
            var  beginLineNumber = lineNumber;
            ScanContentResult result;
            Stream            content;

            OnMimeContentBegin(part, beginOffset);

            if (persistent)
            {
                using (var measured = new MeasuringStream()) {
                    result = await ScanContentAsync(measured, true, cancellationToken).ConfigureAwait(false);

                    endOffset = beginOffset + measured.Length;
                }

                content = new BoundStream(stream, beginOffset, endOffset, true);
            }
            else
            {
                content = new MemoryBlockStream();
                result  = await ScanContentAsync(content, true, cancellationToken).ConfigureAwait(false);

                content.Seek(0, SeekOrigin.Begin);
                endOffset = beginOffset + content.Length;
            }

            OnMimeContentEnd(part, endOffset);
            OnMimeContentOctets(part, endOffset - beginOffset);
            OnMimeContentLines(part, lineNumber - beginLineNumber);

            if (!result.IsEmpty)
            {
                part.Content = new MimeContent(content, part.ContentTransferEncoding)
                {
                    NewLineFormat = result.Format
                }
            }
            ;
            else
            {
                content.Dispose();
            }
        }
示例#7
0
		public void TestBasicFunctionality ()
		{
			var multipart = new Multipart ();

			Assert.IsNotNullOrEmpty (multipart.Boundary, "Boundary");
			Assert.IsFalse (multipart.IsReadOnly, "IsReadOnly");

			multipart.Boundary = "__Next_Part_123";

			Assert.AreEqual ("__Next_Part_123", multipart.Boundary);

			var generic = new MimePart ("application", "octet-stream") { ContentObject = new ContentObject (new MemoryStream ()), IsAttachment = true };
			var plain = new TextPart ("plain") { Text = "This is some plain text." };

			multipart.Add (generic);
			multipart.Insert (0, plain);

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

			Assert.IsTrue (multipart.Contains (generic), "Contains");
			Assert.AreEqual (0, multipart.IndexOf (plain), "IndexOf");
			Assert.IsTrue (multipart.Remove (generic), "Remove");
			Assert.IsFalse (multipart.Remove (generic), "Remove 2nd time");

			multipart.RemoveAt (0);

			Assert.AreEqual (0, multipart.Count, "Count");

			multipart.Add (generic);
			multipart.Add (plain);

			Assert.AreEqual (generic, multipart[0]);
			Assert.AreEqual (plain, multipart[1]);

			multipart[0] = plain;
			multipart[1] = generic;

			Assert.AreEqual (plain, multipart[0]);
			Assert.AreEqual (generic, multipart[1]);

			multipart.Clear ();

			Assert.AreEqual (0, multipart.Count, "Count");
		}
示例#8
0
        async Task <MimeEntity> CreateAttachmentAsync(ContentType contentType, string path, Stream stream, CancellationToken cancellationToken)
        {
            var        fileName = GetFileName(path);
            MimeEntity attachment;

            if (contentType.IsMimeType("message", "rfc822"))
            {
                var message = await MimeMessage.LoadAsync(stream, cancellationToken).ConfigureAwait(false);

                attachment = new MessagePart {
                    Message = message
                };
            }
            else
            {
                MimePart part;

                if (contentType.IsMimeType("text", "*"))
                {
                    // TODO: should we try to auto-detect charsets if no charset parameter is specified?
                    part = new TextPart(contentType);
                }
                else
                {
                    part = new MimePart(contentType);
                }

                await LoadContentAsync(part, stream, cancellationToken).ConfigureAwait(false);

                attachment = part;
            }

            attachment.ContentDisposition          = new ContentDisposition(linked ? ContentDisposition.Inline : ContentDisposition.Attachment);
            attachment.ContentDisposition.FileName = fileName;
            attachment.ContentType.Name            = fileName;

            if (linked)
            {
                attachment.ContentLocation = new Uri(fileName, UriKind.Relative);
            }

            return(attachment);
        }
示例#9
0
        /// <summary>
        /// Prepare a RFC 5322 message searialized from a Contxt object
        /// </summary>
        /// <returns></returns>
        public MimePart BuildMimePart()
        {
            var mimePart = new MimePart(_directContext.ContentType)
            {
                ContentDisposition      = new ContentDisposition(ContentDisposition.Attachment),
                ContentTransferEncoding = _directContext.ContentTransferEncoding
            };

            var contentDist = _directContext.ContentDisposition;

            mimePart.ContentDisposition.FileName = contentDist.FileName;
            mimePart.ContentId = _directContext.ContentId;

            var contextBodyStream = new MemoryStream(Encoding.UTF8.GetBytes(_directContext.Metadata.Deserialize()));

            mimePart.ContentObject = new ContentObject(contextBodyStream);

            return(mimePart);
        }
示例#10
0
        void LoadContent(MimePart attachment, string fileName, byte[] data)
        {
            var content = new MemoryBlockStream();
            var filter = new BestEncodingFilter();
            int index, length;

            filter.Flush(data, 0, data.Length, out index, out length);
            content.Write(data, 0, data.Length);

            content.Position = 0;

            if (linked)
            {
                attachment.ContentLocation = new Uri(Path.GetFileName(fileName), UriKind.Relative);
            }

            attachment.ContentTransferEncoding = filter.GetBestEncoding(EncodingConstraint.SevenBit);
            attachment.ContentObject           = new ContentObject(content, ContentEncoding.Default);
        }
示例#11
0
        static void LoadContent(MimePart attachment, Stream stream)
        {
            var content = new MemoryBlockStream();
            var filter = new BestEncodingFilter();
            var buf = new byte[4096];
            int index, length;
            int nread;

            while ((nread = stream.Read(buf, 0, buf.Length)) > 0)
            {
                filter.Filter(buf, 0, nread, out index, out length);
                content.Write(buf, 0, nread);
            }

            filter.Flush(buf, 0, 0, out index, out length);
            content.Position = 0;

            attachment.ContentTransferEncoding = filter.GetBestEncoding(EncodingConstraint.SevenBit);
            attachment.ContentObject           = new ContentObject(content);
        }
		public void TestDocumentRoot ()
		{
			var gif = new MimePart ("image", "gif") { ContentDisposition = new ContentDisposition (ContentDisposition.Inline) { FileName = "empty.gif" }, ContentId = MimeUtils.GenerateMessageId () };
			var jpg = new MimePart ("image", "jpg") { ContentDisposition = new ContentDisposition (ContentDisposition.Inline) { FileName = "empty.jpg" }, ContentId = MimeUtils.GenerateMessageId () };
			var html = new TextPart ("html") { Text = "This is the html body...", ContentId = MimeUtils.GenerateMessageId () };
			var related = new MultipartRelated (gif, jpg, html);
			string start;

			related.ContentType.Parameters["type"] = "text/html";
			related.ContentType.Parameters["start"] = "<" + html.ContentId + ">";

			Assert.AreEqual (3, related.Count, "Initial Count");
			Assert.AreEqual (html, related.Root, "Initial Root");
			Assert.AreEqual (html, related[2], "Initial Root should be the 3rd item.");

			var root = new TextPart ("html") { Text = "This is the replacement root document..." };

			related.Root = root;

			Assert.AreEqual (3, related.Count, "Count");
			Assert.AreEqual (root, related.Root, "Root");
			Assert.AreEqual (root, related[2], "Root should be the 3rd item.");
			Assert.IsNotNullOrEmpty (root.ContentId, "Root's Content-Id should not be null.");

			start = "<" + root.ContentId + ">";

			Assert.AreEqual (start, related.ContentType.Parameters["start"], "The start parameter does not match.");

			related.Clear ();
			related.Add (gif);
			related.Add (jpg);
			related.Root = html;

			Assert.AreEqual (3, related.Count, "Count");
			Assert.AreEqual (html, related.Root, "Root");
			Assert.AreEqual (html, related[0], "Root should be the 1st item.");

			// Note: MimeKit no longer sets the "start" parameter if the root is the first MIME part due to a bug in Thunderbird.
			Assert.IsNull (related.ContentType.Parameters["start"], "The start parameter should be null.");
		}
示例#13
0
        async Task ConstructMimePartAsync(MimePart part, CancellationToken cancellationToken)
        {
            ScanContentResult result;
            Stream            content;

            if (persistent)
            {
                long begin = GetOffset(inputIndex);
                long end;

                using (var measured = new MeasuringStream()) {
                    result = await ScanContentAsync(measured, true, cancellationToken).ConfigureAwait(false);

                    end = begin + measured.Length;
                }

                content = new BoundStream(stream, begin, end, true);
            }
            else
            {
                content = new MemoryBlockStream();
                result  = await ScanContentAsync(content, true, cancellationToken).ConfigureAwait(false);

                content.Seek(0, SeekOrigin.Begin);
            }

            if (!result.IsEmpty)
            {
                part.Content = new MimeContent(content, part.ContentTransferEncoding)
                {
                    NewLineFormat = result.Format
                }
            }
            ;
            else
            {
                content.Dispose();
            }
        }
示例#14
0
        static async Task LoadContentAsync(MimePart attachment, Stream stream, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var content = new MemoryBlockStream();

            if (attachment.ContentType.IsMimeType("text", "*"))
            {
                var buf = ArrayPool <byte> .Shared.Rent(BufferLength);

                var filter = new BestEncodingFilter();
                int index, length;
                int nread;

                try {
                    while ((nread = await stream.ReadAsync(buf, 0, BufferLength, cancellationToken).ConfigureAwait(false)) > 0)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        filter.Filter(buf, 0, nread, out index, out length);
                        content.Write(buf, 0, nread);
                    }

                    filter.Flush(buf, 0, 0, out index, out length);
                } finally {
                    ArrayPool <byte> .Shared.Return(buf);
                }

                attachment.ContentTransferEncoding = filter.GetBestEncoding(EncodingConstraint.SevenBit);
            }
            else
            {
                attachment.ContentTransferEncoding = ContentEncoding.Base64;
                await stream.CopyToAsync(content, 4096, cancellationToken).ConfigureAwait(false);
            }

            content.Position = 0;

            attachment.Content = new MimeContent(content);
        }
示例#15
0
        /// <summary>
        /// Add the specified attachment.
        /// </summary>
        /// <remarks>
        /// <para>Adds the specified file as an attachment.</para>
        /// </remarks>
        /// <param name="fileName">The name of the file.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="fileName"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// The specified file path is empty.
        /// </exception>
        /// <exception cref="System.IO.FileNotFoundException">
        /// The specified file could not be found.
        /// </exception>
        /// <exception cref="System.UnauthorizedAccessException">
        /// The user does not have access to read the specified file.
        /// </exception>
        /// <exception cref="System.IO.IOException">
        /// An I/O error occurred.
        /// </exception>
        public void Add(string fileName)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }

            if (fileName.Length == 0)
            {
                throw new ArgumentException("The specified file path is empty.", "fileName");
            }

            var attachment = new MimePart(GetMimeType(Path.GetExtension(fileName).ToLowerInvariant()))
            {
                FileName     = Path.GetFileName(fileName),
                IsAttachment = true
            };

            LoadContent(attachment, fileName);

            attachments.Add(attachment);
        }
示例#16
0
        /// <summary>
        /// Add the specified attachment.
        /// </summary>
        /// <remarks>
        /// <para>Adds the specified data as an attachment using the supplied Content-Type.</para>
        /// <para>The file name parameter is used to set the Content-Location.</para>
        /// <para>For a list of known mime-types and their associated file extensions, see
        /// http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types</para>
        /// </remarks>
        /// <param name="fileName">The name of the file.</param>
        /// <param name="data">The file data.</param>
        /// <param name="contentType">The mime-type of the file.</param>
        /// <exception cref="System.ArgumentNullException">
        /// <para><paramref name="fileName"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="data"/> is <c>null</c>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="contentType"/> is <c>null</c>.</para>
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// <para>The specified file path is empty.</para>
        /// <para>-or-</para>
        /// <para>The data is empty.</para>
        /// </exception>
        public void Add(string fileName, byte[] data, ContentType contentType)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException("fileName");
            }

            if (fileName.Length == 0)
            {
                throw new ArgumentException("The specified file path is empty.", "fileName");
            }

            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            if (data.Length == 0)
            {
                throw new ArgumentException("The data is empty.", "data");
            }

            if (contentType == null)
            {
                throw new ArgumentNullException("contentType");
            }

            var attachment = new MimePart(contentType)
            {
                FileName     = Path.GetFileName(fileName),
                IsAttachment = true
            };

            LoadContent(attachment, fileName, data);

            attachments.Add(attachment);
        }
示例#17
0
        bool TryGetImage(string url, out MimePart image)
        {
            UriKind kind;
            Uri uri;

            if (Uri.IsWellFormedUriString(url, UriKind.Absolute))
                kind = UriKind.Absolute;
            else if (Uri.IsWellFormedUriString(url, UriKind.Relative))
                kind = UriKind.Relative;
            else
                kind = UriKind.RelativeOrAbsolute;

            try
            {
                uri = new Uri(url, kind);
            }
            catch (UriFormatException)
            {
                image = null;
                return false;
            }

            for (int i = _stack.Count - 1; i >= 0; i--)
            {
                int index;
                if ((index = _stack[i].IndexOf(uri)) == -1)
                    continue;

                image = _stack[i][index] as MimePart;
                return image != null;
            }

            image = null;

            return false;
        }
        static void LoadContent(MimePart attachment, Stream stream)
        {
            var content = new MemoryBlockStream();

            if (attachment.ContentType.IsMimeType("text", "*"))
            {
                var buf = ArrayPool <byte> .Shared.Rent(BufferLength);

                var filter = new BestEncodingFilter();
                int index, length;
                int nread;

                try {
                    while ((nread = stream.Read(buf, 0, BufferLength)) > 0)
                    {
                        filter.Filter(buf, 0, nread, out index, out length);
                        content.Write(buf, 0, nread);
                    }

                    filter.Flush(buf, 0, 0, out index, out length);
                } finally {
                    ArrayPool <byte> .Shared.Return(buf);
                }

                attachment.ContentTransferEncoding = filter.GetBestEncoding(EncodingConstraint.SevenBit);
            }
            else
            {
                attachment.ContentTransferEncoding = ContentEncoding.Base64;
                stream.CopyTo(content, 4096);
            }

            content.Position = 0;

            attachment.Content = new MimeContent(content);
        }
示例#19
0
 public static void DownloadAttachement(MimePart entity, string filepath)
 {
     using (var stream = File.Create(filepath))
     {
         entity.ContentObject.DecodeTo(stream);
     }
 }
        public void SyncUsingMimeKit(string workspace, string project)
        {
            DynamicJsonObject toCreate = new DynamicJsonObject();

            toCreate[RALLY.WorkSpace] = workspace;
            toCreate[RALLY.Project]   = project;
            DynamicJsonObject attachmentContent   = new DynamicJsonObject();
            DynamicJsonObject attachmentContainer = new DynamicJsonObject();
            CreateResult      createUserStory;
            CreateResult      attachmentContentCreateResult;
            CreateResult      attachmentContainerCreateResult;

            string[] allAttachments;
            Dictionary <string, string> attachmentsDictionary = new Dictionary <string, string>();
            string emailSubject;
            string emailBody;
            string userStoryReference;
            int    anotherOne = 0;
            string base64String;
            string attachmentFileName;
            string fileName;

            EnsureRallyIsAuthenticated();

            using (var client = new ImapClient())
            {
                client.ServerCertificateValidationCallback = (s, c, ch, e) => true;
                client.Connect(EMAIL.GoogleImapHost, EMAIL.ImapPort, SecureSocketOptions.SslOnConnect);
                client.AuthenticationMechanisms.Remove(EMAIL.GoogleOAuth);
                client.Authenticate(EMAIL.GoogleUsername, EMAIL.GenericPassword);

                client.Inbox.Open(FolderAccess.ReadWrite);
                IMailFolder      inboxFolder = client.GetFolder("Inbox");
                IList <UniqueId> uids        = client.Inbox.Search(SearchQuery.All);

                foreach (UniqueId uid in uids)
                {
                    MimeMessage message = inboxFolder.GetMessage(uid);
                    emailSubject = message.Subject;
                    emailBody    = message.TextBody;

                    if (emailSubject.IsEmpty())
                    {
                        emailSubject = "<No Subject User Story>";
                    }

                    toCreate[RALLY.Name]        = (emailSubject);
                    toCreate[RALLY.Description] = (emailBody);
                    createUserStory             = _rallyRestApi.Create(RALLY.HierarchicalRequirement, toCreate);

                    foreach (MimeEntity attachment in message.BodyParts)
                    {
                        string attachmentFile     = attachment.ContentDisposition?.FileName ?? attachment.ContentType.Name;
                        string attachmentFilePath = Concat(STORAGE.MimeKitAttachmentsDirectory, Path.GetFileName(attachmentFile));

                        if (!IsNullOrWhiteSpace(attachmentFile))
                        {
                            if (File.Exists(attachmentFilePath))
                            {
                                string extension = Path.GetExtension(attachmentFilePath);
                                string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(attachmentFilePath);
                                attachmentFile = Format(fileNameWithoutExtension + "-{0}" + "{1}", ++anotherOne,
                                                        extension);
                                attachmentFilePath = Path.Combine(STORAGE.MimeKitAttachmentsDirectory,
                                                                  attachmentFile);
                            }

                            using (var attachmentStream = File.Create(attachmentFilePath))
                            {
                                MimeKit.MimePart part = (MimeKit.MimePart)attachment;
                                part.ContentObject.DecodeTo(attachmentStream);
                            }

                            Console.WriteLine("Downloaded: " + attachmentFile);
                        }
                    }

                    allAttachments = Directory.GetFiles(STORAGE.MimeKitAttachmentsDirectory);
                    foreach (string file in allAttachments)
                    {
                        base64String       = FileToBase64(file);
                        attachmentFileName = Path.GetFileName(file);
                        fileName           = Empty;

                        if (!(attachmentsDictionary.TryGetValue(base64String, out fileName)))
                        {
                            Console.WriteLine("Added to Dictionary: " + file);
                            attachmentsDictionary.Add(base64String, attachmentFileName);
                        }

                        File.Delete(file);
                    }

                    //for each email message - upload it to Rally
                    foreach (KeyValuePair <string, string> attachmentPair in attachmentsDictionary)
                    {
                        try
                        {
                            //create attachment content
                            attachmentContent[RALLY.Content] = attachmentPair.Key;
                            attachmentContentCreateResult    = _rallyRestApi.Create(RALLY.AttachmentContent,
                                                                                    attachmentContent);
                            userStoryReference = attachmentContentCreateResult.Reference;

                            //create attachment contianer
                            attachmentContainer[RALLY.Artifact]    = createUserStory.Reference;
                            attachmentContainer[RALLY.Content]     = userStoryReference;
                            attachmentContainer[RALLY.Name]        = attachmentPair.Value;
                            attachmentContainer[RALLY.Description] = RALLY.EmailAttachment;
                            attachmentContainer[RALLY.ContentType] = "file/";

                            //Create & associate the attachment
                            attachmentContainerCreateResult = _rallyRestApi.Create(RALLY.Attachment,
                                                                                   attachmentContainer);
                        }
                        catch (WebException e)
                        {
                            Console.WriteLine("Attachment: " + e.Message);
                        }
                    }
                    attachmentsDictionary.Clear();

                    Console.WriteLine("User Story: " + message.Subject);
                }
            }
        }
示例#21
0
		static void ExtractAttachments (TnefReader reader, BodyBuilder builder)
		{
			var attachMethod = TnefAttachMethod.ByValue;
			var filter = new BestEncodingFilter ();
			var prop = reader.TnefPropertyReader;
			MimePart attachment = null;
			int outIndex, outLength;
			TnefAttachFlags flags;
			string[] mimeType;
			byte[] attachData;
			DateTime time;
			string text;

			Console.WriteLine ("Extracting attachments...");

			do {
				if (reader.AttributeLevel != TnefAttributeLevel.Attachment)
					Assert.Fail ("Expected attachment attribute level: {0}", reader.AttributeLevel);

				switch (reader.AttributeTag) {
				case TnefAttributeTag.AttachRenderData:
					Console.WriteLine ("Attachment Attribute: {0}", reader.AttributeTag);
					attachMethod = TnefAttachMethod.ByValue;
					attachment = new MimePart ();
					break;
				case TnefAttributeTag.Attachment:
					Console.WriteLine ("Attachment Attribute: {0}", reader.AttributeTag);
					if (attachment == null)
						break;

					while (prop.ReadNextProperty ()) {
						switch (prop.PropertyTag.Id) {
						case TnefPropertyId.AttachLongFilename:
							attachment.FileName = prop.ReadValueAsString ();

							Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.FileName);
							break;
						case TnefPropertyId.AttachFilename:
							if (attachment.FileName == null) {
								attachment.FileName = prop.ReadValueAsString ();
								Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.FileName);
							} else {
								Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, prop.ReadValueAsString ());
							}
							break;
						case TnefPropertyId.AttachContentLocation:
							text = prop.ReadValueAsString ();
							if (Uri.IsWellFormedUriString (text, UriKind.Absolute))
								attachment.ContentLocation = new Uri (text, UriKind.Absolute);
							else if (Uri.IsWellFormedUriString (text, UriKind.Relative))
								attachment.ContentLocation = new Uri (text, UriKind.Relative);
							Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, text);
							break;
						case TnefPropertyId.AttachContentBase:
							text = prop.ReadValueAsString ();
							attachment.ContentBase = new Uri (text, UriKind.Absolute);
							Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, text);
							break;
						case TnefPropertyId.AttachContentId:
							attachment.ContentId = prop.ReadValueAsString ();
							Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.ContentId);
							break;
						case TnefPropertyId.AttachDisposition:
							text = prop.ReadValueAsString ();
							if (attachment.ContentDisposition == null)
								attachment.ContentDisposition = new ContentDisposition (text);
							else
								attachment.ContentDisposition.Disposition = text;
							Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, text);
							break;
						case TnefPropertyId.AttachMethod:
							attachMethod = (TnefAttachMethod) prop.ReadValueAsInt32 ();
							Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachMethod);
							break;
						case TnefPropertyId.AttachMimeTag:
							text = prop.ReadValueAsString ();
							mimeType = text.Split ('/');
							if (mimeType.Length == 2) {
								attachment.ContentType.MediaType = mimeType[0].Trim ();
								attachment.ContentType.MediaSubtype = mimeType[1].Trim ();
							}
							Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, text);
							break;
						case TnefPropertyId.AttachFlags:
							flags = (TnefAttachFlags) prop.ReadValueAsInt32 ();
							if ((flags & TnefAttachFlags.RenderedInBody) != 0) {
								if (attachment.ContentDisposition == null)
									attachment.ContentDisposition = new ContentDisposition (ContentDisposition.Inline);
								else
									attachment.ContentDisposition.Disposition = ContentDisposition.Inline;
							}
							Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, flags);
							break;
						case TnefPropertyId.AttachData:
							var stream = prop.GetRawValueReadStream ();
							var content = new MemoryStream ();
							var guid = new byte[16];

							if (attachMethod == TnefAttachMethod.EmbeddedMessage) {
								var tnef = new TnefPart ();

								foreach (var param in attachment.ContentType.Parameters)
									tnef.ContentType.Parameters[param.Name] = param.Value;

								if (attachment.ContentDisposition != null)
									tnef.ContentDisposition = attachment.ContentDisposition;

								attachment = tnef;
							}

							stream.Read (guid, 0, 16);

							stream.CopyTo (content, 4096);

							var buffer = content.GetBuffer ();
							filter.Flush (buffer, 0, (int) content.Length, out outIndex, out outLength);
							attachment.ContentTransferEncoding = filter.GetBestEncoding (EncodingConstraint.SevenBit);
							attachment.ContentObject = new ContentObject (content);
							filter.Reset ();

							Console.WriteLine ("Attachment Property: {0} has GUID {1}", prop.PropertyTag.Id, new Guid (guid));

							builder.Attachments.Add (attachment);
							break;
						case TnefPropertyId.DisplayName:
							attachment.ContentType.Name = prop.ReadValueAsString ();
							Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.ContentType.Name);
							break;
						case TnefPropertyId.AttachSize:
							if (attachment.ContentDisposition == null)
								attachment.ContentDisposition = new ContentDisposition ();

							attachment.ContentDisposition.Size = prop.ReadValueAsInt64 ();
							Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.ContentDisposition.Size.Value);
							break;
						default:
							Console.WriteLine ("Attachment Property (unhandled): {0} = {1}", prop.PropertyTag.Id, prop.ReadValue ());
							break;
						}
					}
					break;
				case TnefAttributeTag.AttachData:
					Console.WriteLine ("Attachment Attribute: {0}", reader.AttributeTag);
					if (attachment == null || attachMethod != TnefAttachMethod.ByValue)
						break;

					attachData = prop.ReadValueAsBytes ();
					filter.Flush (attachData, 0, attachData.Length, out outIndex, out outLength);
					attachment.ContentTransferEncoding = filter.GetBestEncoding (EncodingConstraint.SevenBit);
					attachment.ContentObject = new ContentObject (new MemoryStream (attachData, false));
					filter.Reset ();

					builder.Attachments.Add (attachment);
					break;
				case TnefAttributeTag.AttachCreateDate:
					time = prop.ReadValueAsDateTime ();

					if (attachment != null) {
						if (attachment.ContentDisposition == null)
							attachment.ContentDisposition = new ContentDisposition ();

						attachment.ContentDisposition.CreationDate = time;
					}

					Console.WriteLine ("Attachment Attribute: {0} = {1}", reader.AttributeTag, time);
					break;
				case TnefAttributeTag.AttachModifyDate:
					time = prop.ReadValueAsDateTime ();

					if (attachment != null) {
						if (attachment.ContentDisposition == null)
							attachment.ContentDisposition = new ContentDisposition ();

						attachment.ContentDisposition.ModificationDate = time;
					}

					Console.WriteLine ("Attachment Attribute: {0} = {1}", reader.AttributeTag, time);
					break;
				case TnefAttributeTag.AttachTitle:
					text = prop.ReadValueAsString ();

					if (attachment != null && string.IsNullOrEmpty (attachment.FileName))
						attachment.FileName = text;

					Console.WriteLine ("Attachment Attribute: {0} = {1}", reader.AttributeTag, text);
					break;
				default:
					Console.WriteLine ("Attachment Attribute (unhandled): {0} = {1}", reader.AttributeTag, prop.ReadValue ());
					break;
				}
			} while (reader.ReadNextAttribute ());
		}
        /// <summary>
        /// Rally is authenticated in the constructor
        /// </summary>
        /// <param name="workspace"></param>

        public void SyncThroughLabels(string workspace)
        {
            #region variables
            SlackClient       _slackClient = new SlackClient(SLACK.SlackApiToken, 100);
            DynamicJsonObject toCreate     = new DynamicJsonObject();
            toCreate[RALLY.WorkSpace] = workspace;
            DynamicJsonObject           attachmentContent   = new DynamicJsonObject();
            DynamicJsonObject           attachmentContainer = new DynamicJsonObject();
            CreateResult                createUserStory;
            CreateResult                attachmentContentCreateResult;
            CreateResult                attachmentContainerCreateResult;
            string[]                    allAttachments;
            Dictionary <string, string> attachmentsDictionary = new Dictionary <string, string>();
            string userStorySubject;
            string userStoryDescription;
            string userStoryReference;
            string attachmentReference;
            int    anotherOne = 0;
            string base64String;
            string attachmentFileName;
            string fileName;
            string _objectId;
            string _userStoryUrl;
            string _slackAttachmentString;
            string slackChannel;
            #endregion

            using (ImapClient client = new ImapClient())
            {
                AuthenticateWithGoogleImap(client);

                client.Inbox.Open(FolderAccess.ReadWrite);
                IMailFolder parentFolder    = client.GetFolder(EMAIL.EnrollmentStudentServicesFolder);
                IMailFolder processedFolder = parentFolder.GetSubfolder(RALLYQUERY.ProcessedEnrollmentStudentServices);

                foreach (IMailFolder childFolder in parentFolder.GetSubfolders())
                {
                    #region Folders
                    if (childFolder.Name.Equals(RALLYQUERY.GmailFolderCatalyst2016))
                    {
                        toCreate[RALLY.Project] = RALLYQUERY.ProjectCatalyst2016;
                        slackChannel            = SLACK.Channelcatalyst2016;
                    }
                    else if (childFolder.Name.Equals(RALLYQUERY.GmailFolderHonorsEnhancements))
                    {
                        toCreate[RALLY.Project] = RALLYQUERY.ProjectHonorsEnhancements;
                        slackChannel            = SLACK.ChannelHonorsEnhancements;
                    }
                    else if (childFolder.Name.Equals(RALLYQUERY.GmailFolderPalHelp))
                    {
                        toCreate[RALLY.Project] = RALLYQUERY.ProjectPalHelp;
                        slackChannel            = SLACK.ChannelPalHelp;
                    }
                    else if (childFolder.Name.Equals(RALLYQUERY.GmailFolderPciAzureTouchNetImplementation))
                    {
                        toCreate[RALLY.Project] = RALLYQUERY.ProjectPciAzureTouchNetImplementation;
                        slackChannel            = SLACK.ChannelAzureTouchNet;
                    }
                    else
                    {
                        toCreate[RALLY.Project] = RALLYQUERY.ProjectScrumptious;
                        slackChannel            = SLACK.ChannelScrumptious;
                    }
                    #endregion

                    Console.WriteLine(childFolder.Name);
                    childFolder.Open(FolderAccess.ReadWrite);
                    IList <UniqueId> childFolderMsgUniqueIds = childFolder.Search(SearchQuery.NotSeen);

                    if (childFolderMsgUniqueIds.Any())
                    {
                        foreach (UniqueId uid in childFolderMsgUniqueIds)
                        {
                            MimeMessage message = childFolder.GetMessage(uid);
                            userStorySubject     = message.Subject;
                            userStoryDescription =
                                "From: " + message.From +
                                "<br>" + "Date Sent: " + message.Date + "</br>" +
                                "<br>" + "Subject: " + userStorySubject + "</br>" +
                                "<br>" + "Request: " + message.GetTextBody(TextFormat.Plain) + "<br>";

                            if (userStorySubject.IsEmpty())
                            {
                                userStorySubject = "<No Subject User Story>";
                            }

                            toCreate[RALLY.Name]        = userStorySubject;
                            toCreate[RALLY.Description] = userStoryDescription;
                            createUserStory             = _rallyRestApi.Create(RALLY.HierarchicalRequirement, toCreate);
                            userStoryReference          = createUserStory.Reference;

                            #region Download Attachments

                            foreach (MimeEntity attachment in message.BodyParts)
                            {
                                string attachmentFile = attachment.ContentDisposition?.FileName ??
                                                        attachment.ContentType.Name;
                                string attachmentFilePath = Concat(STORAGE.MimeKitAttachmentsDirectoryWork,
                                                                   Path.GetFileName(attachmentFile));

                                if (!IsNullOrWhiteSpace(attachmentFile))
                                {
                                    if (File.Exists(attachmentFilePath))
                                    {
                                        string extension = Path.GetExtension(attachmentFilePath);
                                        string fileNameWithoutExtension =
                                            Path.GetFileNameWithoutExtension(attachmentFilePath);
                                        attachmentFile = Format(fileNameWithoutExtension + "-{0}" + "{1}", ++anotherOne,
                                                                extension);
                                        attachmentFilePath =
                                            Path.Combine(STORAGE.MimeKitAttachmentsDirectoryWork, attachmentFile);
                                    }

                                    using (var attachmentStream = File.Create(attachmentFilePath))
                                    {
                                        MimeKit.MimePart part = (MimeKit.MimePart)attachment;
                                        part.ContentObject.DecodeTo(attachmentStream);
                                    }

                                    Console.WriteLine("Downloaded: " + attachmentFile);
                                }
                            }

                            #endregion

                            #region Process Attachments

                            allAttachments = Directory.GetFiles(STORAGE.MimeKitAttachmentsDirectoryWork);
                            foreach (string file in allAttachments)
                            {
                                base64String       = FileToBase64(file);
                                attachmentFileName = Path.GetFileName(file);
                                fileName           = Empty;

                                if (!(attachmentsDictionary.TryGetValue(base64String, out fileName)))
                                {
                                    Console.WriteLine("Added to Dictionary: " + file);
                                    attachmentsDictionary.Add(base64String, attachmentFileName);
                                }

                                File.Delete(file);
                            }

                            #endregion

                            #region Upload to Rally
                            foreach (KeyValuePair <string, string> attachmentPair in attachmentsDictionary)
                            {
                                try
                                {
                                    //create attachment content
                                    attachmentContent[RALLY.Content] = attachmentPair.Key;
                                    attachmentContentCreateResult    = _rallyRestApi.Create(
                                        RALLY.AttachmentContent,
                                        attachmentContent);
                                    attachmentReference = attachmentContentCreateResult.Reference;

                                    //create attachment contianer
                                    attachmentContainer[RALLY.Artifact]    = userStoryReference;
                                    attachmentContainer[RALLY.Content]     = attachmentReference;
                                    attachmentContainer[RALLY.Name]        = attachmentPair.Value;
                                    attachmentContainer[RALLY.Description] = RALLY.EmailAttachment;
                                    attachmentContainer[RALLY.ContentType] = "file/";

                                    //Create & associate the attachment
                                    attachmentContainerCreateResult = _rallyRestApi.Create(RALLY.Attachment,
                                                                                           attachmentContainer);
                                    Console.WriteLine("Uploaded to Rally: " + attachmentPair.Value);
                                }
                                catch (WebException e)
                                {
                                    Console.WriteLine("Attachment: " + e.Message);
                                }
                            }
                            attachmentsDictionary.Clear();

                            #endregion

                            #region See and Move

                            childFolder.SetFlags(uid, MessageFlags.Seen, true);
                            childFolder.MoveTo(uid, processedFolder);

                            #endregion

                            #region Slack

                            if (userStoryReference != null)
                            {
                                _objectId              = Ref.GetOidFromRef(userStoryReference);
                                _userStoryUrl          = string.Concat(SLACK.UserStoryUrlFormat, _objectId);
                                _slackAttachmentString = string.Format("User Story: <{0} | {1} >", _userStoryUrl, message.Subject);

                                SlackMessage slackMessage = new SlackMessage
                                {
                                    //Channel is set according to the source of the email message folder
                                    Channel   = slackChannel,
                                    Text      = SLACK.SlackNotificationBanner,
                                    IconEmoji = Emoji.SmallRedTriangle,
                                    Username  = SLACK.SlackUser
                                };

                                SlackAttachment slackAttachment = new SlackAttachment
                                {
                                    Fallback = _slackAttachmentString,
                                    Text     = _slackAttachmentString,
                                    Color    = SLACK.HexColor
                                };

                                slackMessage.Attachments = new List <SlackAttachment> {
                                    slackAttachment
                                };
                                _slackClient.Post(slackMessage);
                            }
                            else
                            {
                                throw new NullReferenceException();
                            }

                            #endregion

                            #region Email
                            using (SmtpClient smtpClient = new SmtpClient())
                            {
                                if (!smtpClient.IsAuthenticated)
                                {
                                    AuthenticateWithGoogleSmtp(smtpClient);
                                }

                                //iterate throught the email addresses, to send the emails
                                List <MailboxAddress> emailNoticationList = new List <MailboxAddress>();
                                emailNoticationList.Add(new MailboxAddress("*****@*****.**"));

                                foreach (var mailboxAddress in emailNoticationList)
                                {
                                    MimeMessage emailNotificationMessage = new MimeMessage();
                                    emailNotificationMessage.From.Add(new MailboxAddress("Rally Integration", EMAIL.GoogleUsername));
                                    emailNotificationMessage.To.Add(mailboxAddress);
                                    emailNotificationMessage.Subject = "Rally Notification: " + userStorySubject;
                                    emailNotificationMessage.Body    = new TextPart("plain")
                                    {
                                        Text = "User Story: " + _userStoryUrl
                                    };

                                    smtpClient.Send(emailNotificationMessage);
                                }

                                //disconnect here...
                                //this will make the program connect and disconnect in a loop
                            }
                            #endregion

                            Console.WriteLine(message.Subject + " Created");
                        }
                    }
                    else
                    {
                        Console.WriteLine(childFolder + "-No Unread Messages");
                    }
                }
                Console.WriteLine("Done");
                client.Disconnect(true);
            }
        }
示例#23
0
		public void TestContentTransferEncoding ()
		{
			var part = new MimePart ();

			Assert.AreEqual (ContentEncoding.Default, part.ContentTransferEncoding);

			part.ContentTransferEncoding = ContentEncoding.EightBit;
			Assert.AreEqual (ContentEncoding.EightBit, part.ContentTransferEncoding);
			Assert.IsTrue (part.Headers.Contains (HeaderId.ContentTransferEncoding), "Expected header to exist");

			Assert.Throws<ArgumentOutOfRangeException> (() => part.ContentTransferEncoding = (ContentEncoding) 500);

			part.ContentTransferEncoding = ContentEncoding.Default;
			Assert.AreEqual (ContentEncoding.Default, part.ContentTransferEncoding);
			Assert.IsFalse (part.Headers.Contains (HeaderId.ContentTransferEncoding), "Expected header to be removed");

			part.Headers.Add (HeaderId.ContentTransferEncoding, "base64");
			Assert.AreEqual (ContentEncoding.Base64, part.ContentTransferEncoding, "Expected ContentTransferEncoding to be set again");

			part.Headers.Remove (HeaderId.ContentTransferEncoding);
			Assert.AreEqual (ContentEncoding.Default, part.ContentTransferEncoding, "Expected ContentTransferEncoding to be default again");

			part.ContentTransferEncoding = ContentEncoding.UUEncode;
			part.Headers.Clear ();
			Assert.AreEqual (ContentEncoding.Default, part.ContentTransferEncoding, "Expected ContentTransferEncoding to be default again");
		}
示例#24
0
		public void TestMimePartStream ()
		{
			byte[] data = Encoding.ASCII.GetBytes ("abcd");


			var msg = new MimePart ("application", "octet-stream",
				new MemoryStream (data)
			);

			var buffer = new MemoryStream ();
			msg.ContentObject.DecodeTo (buffer);
			buffer.Seek (0, SeekOrigin.Begin);

			Assert.AreEqual (ContentEncoding.Default, msg.ContentObject.Encoding, "ContentEncoding is wrong");
			Assert.AreEqual (data, buffer.ToArray (), "ContentEncoding is wrong");
		}
示例#25
0
		public void TestContentLocation ()
		{
			var part = new MimePart ();
			var uri = new Uri ("http://www.google.com");

			Assert.IsNull (part.ContentLocation, "Initial ContentLocation should be null");

			part.ContentLocation = uri;
			Assert.AreEqual (uri, part.ContentLocation, "Expected ContentLocation to be updated");
			Assert.IsTrue (part.Headers.Contains (HeaderId.ContentLocation), "Expected header to exist");

			part.ContentLocation = null;
			Assert.IsNull (part.ContentLocation, "Expected ContentLocation to be null again");
			Assert.IsFalse (part.Headers.Contains (HeaderId.ContentLocation), "Expected header to be removed");

			part.Headers.Add (HeaderId.ContentLocation, uri.OriginalString);
			Assert.AreEqual (uri, part.ContentLocation, "Expected ContentLocation to be set again");

			part.Headers.Remove (HeaderId.ContentLocation);
			Assert.IsNull (part.ContentLocation, "Expected ContentLocation to be null again");

			part.ContentLocation = uri;
			part.Headers.Clear ();
			Assert.IsNull (part.ContentLocation, "Expected ContentLocation to be null again");
		}
示例#26
0
		public void TestContentId ()
		{
			var id = MimeUtils.GenerateMessageId ();
			var part = new MimePart ();

			Assert.IsNull (part.ContentId, "Initial ContentId value should be null");

			part.ContentId = id;
			Assert.AreEqual (id, part.ContentId, "Expected ContentId to be updated");
			Assert.IsTrue (part.Headers.Contains (HeaderId.ContentId), "Expected header to exist");

			part.ContentId = null;
			Assert.IsNull (part.ContentId, "Expected ContentId to be null again");
			Assert.IsFalse (part.Headers.Contains (HeaderId.ContentId), "Expected header to be removed");

			part.Headers.Add (HeaderId.ContentId, string.Format ("<{0}>", id));
			Assert.AreEqual (id, part.ContentId, "Expected ContentId to be set again");

			part.Headers.Remove (HeaderId.ContentId);
			Assert.IsNull (part.ContentId, "Expected ContentId to be null again");

			part.ContentId = id;
			part.Headers.Clear ();
			Assert.IsNull (part.ContentId, "Expected ContentId to be null again");
		}
示例#27
0
		public void TestContentDuration ()
		{
			var part = new MimePart ();

			Assert.IsNull (part.ContentDuration, "Initial ContentDuration value should be null");

			part.ContentDuration = 500;
			Assert.AreEqual (500, part.ContentDuration, "Expected ContentDuration to be updated");
			Assert.IsTrue (part.Headers.Contains (HeaderId.ContentDuration), "Expected header to exist");

			part.ContentDuration = null;
			Assert.IsNull (part.ContentDuration, "Expected ContentDuration to be null again");
			Assert.IsFalse (part.Headers.Contains (HeaderId.ContentDuration), "Expected header to be removed");

			part.Headers.Add (HeaderId.ContentDuration, "500");
			Assert.AreEqual (500, part.ContentDuration, "Expected ContentDuration to be set again");

			part.Headers.Remove (HeaderId.ContentDuration);
			Assert.IsNull (part.ContentDuration, "Expected ContentDuration to be null again");

			part.ContentDuration = 500;
			part.Headers.Clear ();
			Assert.IsNull (part.ContentDuration, "Expected ContentDuration to be null again");
		}
示例#28
0
		/// <summary>
		/// Visit the abstract MIME part entity.
		/// </summary>
		/// <remarks>
		/// Visits the MIME part entity.
		/// </remarks>
		/// <example>
		/// <code language="c#" source="Examples\MimeVisitorExamples.cs" region="HtmlPreviewVisitor" />
		/// </example>
		/// <param name="entity">The MIME part entity.</param>
		protected internal virtual void VisitMimePart (MimePart entity)
		{
			VisitMimeEntity (entity);
		}
示例#29
0
 protected override void VisitMimePart(MimePart entity)
 {
     // realistically, if we've gotten this far, then we can treat this as an attachment
     // even if the IsAttachment property is false.
     _attachments.Add(entity);
 }
示例#30
0
		static MimePart GetMimePart (AttachmentBase item)
		{
			var mimeType = item.ContentType.ToString ();
			var part = new MimePart (ContentType.Parse (mimeType));
			var attachment = item as Attachment;

			if (attachment != null) {
				var disposition = attachment.ContentDisposition.ToString ();
				part.ContentDisposition = ContentDisposition.Parse (disposition);
			}

			switch (item.TransferEncoding) {
			case System.Net.Mime.TransferEncoding.QuotedPrintable:
				part.ContentTransferEncoding = ContentEncoding.QuotedPrintable;
				break;
			case System.Net.Mime.TransferEncoding.Base64:
				part.ContentTransferEncoding = ContentEncoding.Base64;
				break;
			case System.Net.Mime.TransferEncoding.SevenBit:
				part.ContentTransferEncoding = ContentEncoding.SevenBit;
				break;
			}

			if (item.ContentId != null)
				part.ContentId = item.ContentId;

			var stream = new MemoryBlockStream ();
			item.ContentStream.CopyTo (stream);
			stream.Position = 0;

			part.ContentObject = new ContentObject (stream);

			return part;
		}
示例#31
0
        static void ExtractAttachments(TnefReader reader, BodyBuilder builder)
        {
            var filter = new BestEncodingFilter ();
            var prop = reader.TnefPropertyReader;
            MimePart attachment = null;
            int outIndex, outLength;
            byte[] attachData;
            string text;

            Console.WriteLine ("Extracting attachments...");

            do {
                if (reader.AttributeLevel != TnefAttributeLevel.Attachment)
                    Assert.Fail ("Expected attachment attribute level: {0}", reader.AttributeLevel);

                switch (reader.AttributeTag) {
                case TnefAttributeTag.AttachRenderData:
                    attachment = new MimePart ();
                    builder.Attachments.Add (attachment);
                    break;
                case TnefAttributeTag.Attachment:
                    if (attachment == null)
                        break;

                    while (prop.ReadNextProperty ()) {
                        switch (prop.PropertyTag.Id) {
                        case TnefPropertyId.AttachLongFilename:
                            attachment.FileName = prop.ReadValueAsString ();

                            Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.FileName);
                            break;
                        case TnefPropertyId.AttachFilename:
                            if (attachment.FileName == null) {
                                attachment.FileName = prop.ReadValueAsString ();
                                Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.FileName);
                            } else {
                                Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, prop.ReadValueAsString ());
                            }
                            break;
                        case TnefPropertyId.AttachContentLocation:
                            text = prop.ReadValueAsString ();
                            if (Uri.IsWellFormedUriString (text, UriKind.Absolute))
                                attachment.ContentLocation = new Uri (text, UriKind.Absolute);
                            else if (Uri.IsWellFormedUriString (text, UriKind.Relative))
                                attachment.ContentLocation = new Uri (text, UriKind.Relative);
                            Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, text);
                            break;
                        case TnefPropertyId.AttachContentBase:
                            text = prop.ReadValueAsString ();
                            attachment.ContentBase = new Uri (text, UriKind.Absolute);
                            Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, text);
                            break;
                        case TnefPropertyId.AttachContentId:
                            attachment.ContentId = prop.ReadValueAsString ();
                            Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, attachment.ContentId);
                            break;
                        case TnefPropertyId.AttachDisposition:
                            text = prop.ReadValueAsString ();
                            if (attachment.ContentDisposition == null)
                                attachment.ContentDisposition = new ContentDisposition (text);
                            else
                                attachment.ContentDisposition.Disposition = text;
                            Console.WriteLine ("Attachment Property: {0} = {1}", prop.PropertyTag.Id, text);
                            break;
                        case TnefPropertyId.AttachData:
                            if (prop.IsEmbeddedMessage) {
                                Console.WriteLine ("Attachment Property: {0} is an EmbeddedMessage", prop.PropertyTag.Id);
                                var stream = prop.GetRawValueReadStream ();
                                using (var tnef = new TnefReader (stream, reader.MessageCodepage, reader.ComplianceMode)) {
                                    var embedded = ExtractTnefMessage (tnef);
                                    Console.WriteLine ("embedded attachments = {0}", embedded.BodyParts.Count ());
                                    foreach (var part in embedded.BodyParts)
                                        builder.Attachments.Add (part);
                                }
                            } else {
                                Console.WriteLine ("Attachment Property: {0} is not an EmbeddedMessage", prop.PropertyTag.Id);
                            }
                            break;
                        default:
                            Console.WriteLine ("Attachment Property (unhandled): {0} = {1}", prop.PropertyTag.Id, prop.ReadValue ());
                            break;
                        }
                    }
                    break;
                case TnefAttributeTag.AttachData:
                    if (attachment == null)
                        break;

                    attachData = prop.ReadValueAsBytes ();
                    filter.Flush (attachData, 0, attachData.Length, out outIndex, out outLength);
                    attachment.ContentTransferEncoding = filter.GetBestEncoding (EncodingConstraint.SevenBit);
                    attachment.ContentObject = new ContentObject (new MemoryStream (attachData, false));
                    filter.Reset ();
                    break;
                default:
                    Console.WriteLine ("Attachment Attribute (unhandled): {0} = {1}", reader.AttributeTag, prop.ReadValue ());
                    break;
                }
            } while (reader.ReadNextAttribute ());
        }
示例#32
0
		public void TestContentBase ()
		{
			var relative = new Uri ("relative", UriKind.Relative);
			var uri = new Uri ("http://www.google.com");
			var part = new MimePart ();

			Assert.IsNull (part.ContentBase, "Initial ContentBase should be null");

			Assert.Throws<ArgumentException> (() => part.ContentBase = relative);

			part.ContentBase = uri;
			Assert.AreEqual (uri, part.ContentBase, "Expected ContentBase to be updated");
			Assert.IsTrue (part.Headers.Contains (HeaderId.ContentBase), "Expected header to exist");

			part.ContentBase = null;
			Assert.IsNull (part.ContentBase, "Expected ContentBase to be null again");
			Assert.IsFalse (part.Headers.Contains (HeaderId.ContentBase), "Expected header to be removed");

			part.Headers.Add (HeaderId.ContentBase, uri.OriginalString);
			Assert.AreEqual (uri, part.ContentBase, "Expected ContentBase to be set again");

			part.Headers.Remove (HeaderId.ContentBase);
			Assert.IsNull (part.ContentBase, "Expected ContentBase to be null again");

			part.ContentBase = uri;
			part.Headers.Clear ();
			Assert.IsNull (part.ContentBase, "Expected ContentBase to be null again");
		}
示例#33
0
		// Save the image to our temp directory and return a "file://" url suitable for
		// the browser control to load.
		// Note: if you'd rather embed the image data into the HTML, you can construct a
		// "data:" url instead.
		string SaveImage (MimePart image, string url)
		{
			string fileName = url.Replace (':', '_').Replace ('\\', '_').Replace ('/', '_');

			string path = Path.Combine (tempDir, fileName);

			if (!File.Exists (path)) {
				using (var output = File.Create (path))
					image.ContentObject.DecodeTo (output);
			}

			return "file://" + path.Replace ('\\', '/');
		}
        private void ExtractAttachments(TnefReader reader, BodyBuilder builder)
        {
            var tnefAttachMethod = TnefAttachMethod.ByValue;
            var bestEncodingFilter = new BestEncodingFilter();
            var tnefPropertyReader = reader.TnefPropertyReader;
            MimePart mimePart = null;
            do
            {
                int outputIndex;
                int outputLength;
                switch (reader.AttributeTag)
                {
                    case TnefAttributeTag.AttachData:
                        if (mimePart != null && tnefAttachMethod == TnefAttachMethod.ByValue)
                        {
                            byte[] numArray = tnefPropertyReader.ReadValueAsBytes();
                            bestEncodingFilter.Flush(numArray, 0, numArray.Length, out outputIndex, out outputLength);
                            mimePart.ContentTransferEncoding = bestEncodingFilter.GetBestEncoding(EncodingConstraint.SevenBit, 78);
                            mimePart.ContentObject = new ContentObject(new MemoryStream(numArray, false), ContentEncoding.Default);
                            bestEncodingFilter.Reset();
                            builder.Attachments.Add(mimePart);
                            break;
                        }
                        break;
                    case TnefAttributeTag.AttachRenderData:
                        tnefAttachMethod = TnefAttachMethod.ByValue;
                        mimePart = new MimePart();
                        break;
                    case TnefAttributeTag.Attachment:
                        if (mimePart != null)
                        {
                            while (tnefPropertyReader.ReadNextProperty())
                            {
                                switch (tnefPropertyReader.PropertyTag.Id)
                                {
                                    case TnefPropertyId.AttachData:
                                        using (var rawValueReadStream = tnefPropertyReader.GetRawValueReadStream())
                                        {
                                            using (var memoryStream = new MemoryStream())
                                            {

                                                byte[] buffer = new byte[16];
                                                if (tnefAttachMethod == TnefAttachMethod.EmbeddedMessage)
                                                {
                                                    TnefPart tnefPart = new TnefPart();
                                                    foreach (Parameter parameter in mimePart.ContentType.Parameters)
                                                    {
                                                        tnefPart.ContentType.Parameters[parameter.Name] = parameter.Value;
                                                    }

                                                    if (mimePart.ContentDisposition != null)
                                                    {
                                                        tnefPart.ContentDisposition = mimePart.ContentDisposition;
                                                    }

                                                    mimePart = tnefPart;
                                                }
                                                rawValueReadStream.Read(buffer, 0, 16);
                                                rawValueReadStream.CopyTo(memoryStream, 4096);
                                                byte[] input = memoryStream.ToArray();
                                                bestEncodingFilter.Flush(input, 0, (int)memoryStream.Length, out outputIndex, out outputLength);
                                                mimePart.ContentTransferEncoding = bestEncodingFilter.GetBestEncoding(EncodingConstraint.SevenBit, 78);
                                                mimePart.ContentObject = new ContentObject(memoryStream, ContentEncoding.Default);
                                                bestEncodingFilter.Reset();
                                                builder.Attachments.Add(mimePart);
                                            }
                                        }

                                        continue;
                                    case TnefPropertyId.AttachFilename:
                                        if (String.IsNullOrEmpty(mimePart.FileName))
                                        {
                                            mimePart.FileName = tnefPropertyReader.ReadValueAsString();
                                            continue;
                                        }

                                        continue;
                                    case TnefPropertyId.AttachMethod:
                                        tnefAttachMethod = (TnefAttachMethod)tnefPropertyReader.ReadValueAsInt32();
                                        continue;
                                    case TnefPropertyId.AttachLongFilename:
                                        mimePart.FileName = tnefPropertyReader.ReadValueAsString();
                                        continue;
                                    case TnefPropertyId.AttachMimeTag:
                                        string[] strArray = tnefPropertyReader.ReadValueAsString().Split('/');
                                        if (strArray.Length == 2)
                                        {
                                            mimePart.ContentType.MediaType = strArray[0].Trim();
                                            mimePart.ContentType.MediaSubtype = strArray[1].Trim();
                                            continue;
                                        }

                                        continue;
                                    case TnefPropertyId.AttachContentBase:
                                        var uriString = tnefPropertyReader.ReadValueAsString();
                                        mimePart.ContentBase = new Uri(uriString, UriKind.Absolute);
                                        continue;
                                    case TnefPropertyId.AttachContentId:
                                        mimePart.ContentId = tnefPropertyReader.ReadValueAsString();
                                        continue;
                                    case TnefPropertyId.AttachContentLocation:
                                        var uriString2 = tnefPropertyReader.ReadValueAsString();
                                        if (Uri.IsWellFormedUriString(uriString2, UriKind.Absolute))
                                        {
                                            mimePart.ContentLocation = new Uri(uriString2, UriKind.Absolute);
                                            continue;
                                        }

                                        if (Uri.IsWellFormedUriString(uriString2, UriKind.Relative))
                                        {
                                            mimePart.ContentLocation = new Uri(uriString2, UriKind.Relative);
                                            continue;
                                        }

                                        continue;
                                    case TnefPropertyId.AttachFlags:
                                        if ((tnefPropertyReader.ReadValueAsInt32() & 4) != 0)
                                        {
                                            if (mimePart.ContentDisposition == null)
                                            {
                                                mimePart.ContentDisposition = new ContentDisposition("inline");
                                                continue;
                                            }

                                            mimePart.ContentDisposition.Disposition = "inline";
                                            continue;
                                        }

                                        continue;
                                    case TnefPropertyId.AttachDisposition:
                                        var disposition = tnefPropertyReader.ReadValueAsString();
                                        if (mimePart.ContentDisposition == null)
                                        {
                                            mimePart.ContentDisposition = new ContentDisposition(disposition);
                                            continue;
                                        }

                                        mimePart.ContentDisposition.Disposition = disposition;
                                        continue;
                                    case TnefPropertyId.AttachSize:
                                        if (mimePart.ContentDisposition == null)
                                        {
                                            mimePart.ContentDisposition = new ContentDisposition();
                                        }

                                        mimePart.ContentDisposition.Size = new long?(tnefPropertyReader.ReadValueAsInt64());
                                        continue;
                                    case TnefPropertyId.DisplayName:
                                        mimePart.ContentType.Name = tnefPropertyReader.ReadValueAsString();
                                        continue;
                                    default:
                                        continue;
                                }
                            }
                            break;
                        }
                        break;
                    case TnefAttributeTag.AttachTitle:
                        var name = tnefPropertyReader.ReadValueAsString();
                        if (mimePart != null && String.IsNullOrEmpty(mimePart.FileName))
                        {
                            mimePart.FileName = name;
                            break;
                        }

                        break;
                    case TnefAttributeTag.AttachCreateDate:
                        var creationDateTime = tnefPropertyReader.ReadValueAsDateTime();
                        if (mimePart != null)
                        {
                            if (mimePart.ContentDisposition == null)
                            {
                                mimePart.ContentDisposition = new ContentDisposition();
                            }

                            mimePart.ContentDisposition.CreationDate = new DateTimeOffset(creationDateTime);
                            break;
                        }

                        break;
                    case TnefAttributeTag.AttachModifyDate:
                        var modifyDateTime = tnefPropertyReader.ReadValueAsDateTime();
                        if (mimePart != null)
                        {
                            if (mimePart.ContentDisposition == null)
                            {
                                mimePart.ContentDisposition = new ContentDisposition();
                            }

                            mimePart.ContentDisposition.ModificationDate = new DateTimeOffset(modifyDateTime);
                            break;
                        }

                        break;
                }
            }

            while (reader.ReadNextAttribute());
        }
示例#35
0
		public void TestMimePartContentObject ()
		{
			byte[] data = Encoding.ASCII.GetBytes ("abcd");

			// Checksum will be wrong if content is encoded in any way.
			string checksum;
			using (var md5 = MD5.Create ())
				checksum = Convert.ToBase64String (md5.ComputeHash (data));

			var msg = new MimePart ("application", "octet-stream",
				new ContentObject (new MemoryStream (data), ContentEncoding.Binary)
			);

			Assert.AreEqual (checksum, msg.ComputeContentMd5 (), "Content MD5 is wrong");
			Assert.AreEqual (ContentEncoding.Binary, msg.ContentObject.Encoding, "ContentEncoding is wrong");
		}
示例#36
0
		static MimePart GetMimePart (AttachmentBase item)
		{
			var mimeType = item.ContentType.ToString ();
			var contentType = ContentType.Parse (mimeType);
			var attachment = item as Attachment;
			MimePart part;

			if (contentType.MediaType.Equals ("text", StringComparison.OrdinalIgnoreCase))
				part = new TextPart (contentType);
			else
				part = new MimePart (contentType);

			if (attachment != null) {
				var disposition = attachment.ContentDisposition.ToString ();
				part.ContentDisposition = ContentDisposition.Parse (disposition);
			}

			switch (item.TransferEncoding) {
			case System.Net.Mime.TransferEncoding.QuotedPrintable:
				part.ContentTransferEncoding = ContentEncoding.QuotedPrintable;
				break;
			case System.Net.Mime.TransferEncoding.Base64:
				part.ContentTransferEncoding = ContentEncoding.Base64;
				break;
			case System.Net.Mime.TransferEncoding.SevenBit:
				part.ContentTransferEncoding = ContentEncoding.SevenBit;
				break;
			//case System.Net.Mime.TransferEncoding.EightBit:
			//	part.ContentTransferEncoding = ContentEncoding.EightBit;
			//	break;
			}

			if (item.ContentId != null)
				part.ContentId = item.ContentId;

			var stream = new MemoryBlockStream ();
			item.ContentStream.CopyTo (stream);
			stream.Position = 0;

			part.ContentObject = new ContentObject (stream);

			return part;
		}
示例#37
0
			protected override void VisitMimePart (MimePart entity)
			{
				switch (entity.ContentTransferEncoding) {
				case ContentEncoding.EightBit:
					// if the server supports the 8BITMIME extension, use it...
					if ((Capabilities & SmtpCapabilities.EightBitMime) != 0) {
						SmtpExtensions |= SmtpExtension.EightBitMime;
					} else {
						SmtpExtensions |= SmtpExtension.BinaryMime;
					}
					break;
				case ContentEncoding.Binary:
					SmtpExtensions |= SmtpExtension.BinaryMime;
					break;
				}
			}
示例#38
0
		public void TestContentMd5 ()
		{
			var part = new MimePart ();

			Assert.IsNull (part.ContentMd5, "Initial ContentMd5 value should be null");

			part.ContentMd5 = "XYZ";
			Assert.AreEqual ("XYZ", part.ContentMd5, "Expected ContentMd5 to be updated");
			Assert.IsTrue (part.Headers.Contains (HeaderId.ContentMd5), "Expected header to exist");

			part.ContentMd5 = null;
			Assert.IsNull (part.ContentMd5, "Expected ContentMd5 to be null again");
			Assert.IsFalse (part.Headers.Contains (HeaderId.ContentMd5), "Expected header to be removed");

			part.Headers.Add (HeaderId.ContentMd5, "XYZ");
			Assert.AreEqual ("XYZ", part.ContentMd5, "Expected ContentMd5 to be set again");

			part.Headers.Remove (HeaderId.ContentMd5);
			Assert.IsNull (part.ContentMd5, "Expected ContentMd5 to be null again");

			part.ContentMd5 = "XYZ";
			part.Headers.Clear ();
			Assert.IsNull (part.ContentMd5, "Expected ContentMd5 to be null again");

			Assert.Throws<InvalidOperationException> (() => part.ComputeContentMd5 ());
			Assert.IsFalse (part.VerifyContentMd5 ());
		}
示例#39
0
        string SaveImage(MimePart image, string url)
        {
            string fileName = url.Replace(':', '_').Replace('\\', '_').Replace('/', '_');

            // try to add a file extension for niceness
            switch (image.ContentType.MimeType.ToLowerInvariant())
            {
                case "image/jpeg":
                    fileName += ".jpg";
                    break;
                case "image/png":
                    fileName += ".png";
                    break;
                case "image/gif":
                    fileName += ".gif";
                    break;
            }

            string path = Path.Combine(_tempDir, fileName);

            if (!File.Exists(path))
            {
                using (var output = File.Create(path))
                    image.ContentObject.DecodeTo(output);
            }

            return "file://" + path.Replace('\\', '/');
        }
示例#40
0
		public void TestContentDisposition ()
		{
			var part = new MimePart ();

			Assert.IsNull (part.ContentDisposition, "Initial ContentDisposition should be null");

			part.ContentDisposition = new ContentDisposition (ContentDisposition.Attachment);
			Assert.IsNotNull (part.ContentDisposition, "Expected ContentDisposition to be set");
			Assert.IsTrue (part.Headers.Contains (HeaderId.ContentDisposition), "Expected header to exist");

			part.ContentDisposition = null;
			Assert.IsNull (part.ContentDisposition, "Expected ContentDisposition to be null again");
			Assert.IsFalse (part.Headers.Contains (HeaderId.ContentDisposition), "Expected header to be removed");

			part.Headers.Add (HeaderId.ContentDisposition, "attachment");
			Assert.IsNotNull (part.ContentDisposition, "Expected ContentDisposition to be set again");

			part.Headers.Remove (HeaderId.ContentDisposition);
			Assert.IsNull (part.ContentBase, "Expected ContentDisposition to be null again");

			part.ContentDisposition = new ContentDisposition ();
			part.FileName = "fileName";
			part.Headers.Clear ();
			Assert.IsNull (part.ContentBase, "Expected ContentDisposition to be null again");
		}
示例#41
0
		static string GetImageData (MimePart image)
		{
//			using (var memory = new MemoryStream ()) {
//				image.ContentObject.DecodeTo (memory);
//
//				var buffer = memory.GetBuffer ();
//				int length = (int) memory.Length;
//
//				return string.Format ("data:{0};base64,{1}", image.ContentType.MimeType,
//					Convert.ToBase64String (buffer, 0, length, Base64FormattingOptions.None));
//			}
			return string.Format ("data:{0};base64,[base64 data for {1}]",
				image.ContentType.MimeType, image.ContentId);
		}
 public void Add(MimePart MP)
 {
     attachmentList.Add(MP);
 }
示例#43
0
        ContentEncoding GetFinalEncoding(MimePart part)
        {
            if ((capabilities & SmtpCapabilities.BinaryMime) != 0) {
                // no need to re-encode...
                return part.ContentTransferEncoding;
            }

            if ((capabilities & SmtpCapabilities.EightBitMime) != 0) {
                switch (part.ContentTransferEncoding) {
                case ContentEncoding.Default:
                case ContentEncoding.Binary:
                    break;
                default:
                    // all other Content-Transfer-Encodings are safe to transmit...
                    return part.ContentTransferEncoding;
                }
            }

            switch (part.ContentTransferEncoding) {
            case ContentEncoding.EightBit:
            case ContentEncoding.Default:
            case ContentEncoding.Binary:
                break;
            default:
                // all other Content-Transfer-Encodings are safe to transmit...
                return part.ContentTransferEncoding;
            }

            ContentEncoding encoding;

            if ((capabilities & SmtpCapabilities.BinaryMime) != 0)
                encoding = part.GetBestEncoding (EncodingConstraint.None);
            else if ((capabilities & SmtpCapabilities.EightBitMime) != 0)
                encoding = part.GetBestEncoding (EncodingConstraint.EightBit);
            else
                encoding = part.GetBestEncoding (EncodingConstraint.SevenBit);

            if (encoding == ContentEncoding.SevenBit)
                return encoding;

            part.ContentTransferEncoding = encoding;

            return encoding;
        }
示例#44
0
        unsafe BoundaryType ConstructMimePart(MimePart part, byte* inbuf)
        {
            BoundaryType found;
            Stream content;

            if (persistent) {
                long begin = GetOffset (inputIndex);
                long end;

                using (var measured = new MeasuringStream ()) {
                    found = ScanContent (inbuf, measured, true);
                    end = begin + measured.Length;
                }

                content = new BoundStream (stream, begin, end, true);
            } else {
                content = new MemoryBlockStream ();
                found = ScanContent (inbuf, content, true);
                content.Seek (0, SeekOrigin.Begin);
            }

            part.ContentObject = new ContentObject (content, part.ContentTransferEncoding);

            return found;
        }
示例#45
0
 /// <summary>
 /// Visit the abstract MIME part entity.
 /// </summary>
 /// <remarks>
 /// Visits the MIME part entity.
 /// </remarks>
 /// <example>
 /// <code language="c#" source="Examples\MimeVisitorExamples.cs" region="HtmlPreviewVisitor" />
 /// </example>
 /// <param name="entity">The MIME part entity.</param>
 protected internal virtual void VisitMimePart(MimePart entity)
 {
     VisitMimeEntity(entity);
 }
        private bool StoreEntities(OutgoingEmail email, List<string> attachmentList)
        {
            foreach (string iter in attachmentList)
            {
                FileStream stream = File.OpenRead(iter);
                if (!stream.CanRead)
                {
                    return false;
                }

                string mimeType = MimeTypes.GetMimeType(iter);
                ContentType fileType = ContentType.Parse(mimeType);
                MimePart attachment;
                if (fileType.IsMimeType("text", "*"))
                {
                    attachment = new TextPart(fileType.MediaSubtype);
                    foreach (var param in fileType.Parameters)
                        attachment.ContentType.Parameters.Add(param);
                }
                else
                {
                    attachment = new MimePart(fileType);
                }
                attachment.FileName = Path.GetFileName(iter);
                attachment.IsAttachment = true;

                MemoryBlockStream memoryBlockStream = new MemoryBlockStream();
                BestEncodingFilter encodingFilter = new BestEncodingFilter();
                byte[] fileBuffer = new byte[4096];
                int index, length, bytesRead;

                while ((bytesRead = stream.Read(fileBuffer, 0, fileBuffer.Length)) > 0)
                {
                    encodingFilter.Filter(fileBuffer, 0, bytesRead, out index, out length);
                    memoryBlockStream.Write(fileBuffer, 0, bytesRead);
                }

                encodingFilter.Flush(fileBuffer, 0, 0, out index, out length);
                memoryBlockStream.Position = 0;

                attachment.ContentTransferEncoding = encodingFilter.GetBestEncoding(EncodingConstraint.SevenBit);
                attachment.ContentObject = new ContentObject(memoryBlockStream);

                if (attachment != null) email.AttachmentList.Add(attachment);
            }
            return true;
        }