예제 #1
1
 /*
  * tries to sign a MimeEntity
  */
 public static MimeEntity SignEntity(MimeEntity entity, MailboxAddress signer)
 {
     using (WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(sys.StoreLocation.CurrentUser))
     {
         return MultipartSigned.Create(ctx, signer, DigestAlgorithm.Sha1, entity);
     }
 }
        public EmailAttachment(MimeKit.MimeEntity attachment)
        {
            this.attachment = attachment;

            if (attachment is MimePart)
            {
                MimePart tmp = (MimePart)attachment;
                fileName = tmp.FileName;
            }
        }
예제 #3
0
		static void DumpMimeTree (StringBuilder builder, MimeEntity entity, int depth)
		{
			if (depth > 0)
				builder.Append (new string (' ', depth * 3));

			builder.AppendFormat ("Content-Type: {0}/{1}\n", entity.ContentType.MediaType, entity.ContentType.MediaSubtype);

			if (entity is Multipart) {
				var multipart = (Multipart) entity;
				foreach (var part in multipart)
					DumpMimeTree (builder, part, depth + 1);
			} else if (entity is MessagePart) {
				DumpMimeTree (builder, ((MessagePart) entity).Message.Body, depth + 1);
			}
		}
예제 #4
0
 public PartViewModel(MimeEntity part)
 {
     _part = part;
     var mp = _part as Multipart;
     if (mp != null) { IsExpanded = true; }
 }
예제 #5
0
        /*
         * signs and encrypts message
         */
        internal static MimeEntity SignAndEncrypt(Node ip, MimeMessage msg, MimeEntity body)
        {
            if (ip.GetValue("signed", false))
            {
                // email is signed
                Node signNode = new Node();
                signNode["mime-entity"].Value = body;
                signNode["email-lookup"].Value = ((MailboxAddress)msg.From[0]).Address;
                string activeEvent = "magix.cryptography._sign-mime-entity";

                if (ip.GetValue("encrypt", false))
                {
                    // email is signed and encrypted
                    GetRecipients(msg, signNode);
                    activeEvent = "magix.cryptography._sign_and_encrypt-mime-entity";
                }
                ActiveEvents.Instance.RaiseActiveEvent(
                    typeof(SmtpHelper),
                    activeEvent,
                    signNode);
                body = signNode["mime-entity"].Get<MimeEntity>();
            }
            else if (ip.GetValue("encrypt", false))
            {
                // email is encrypted
                Node encryptNode = new Node();
                encryptNode["mime-entity"].Value = body;

                GetRecipients(msg, encryptNode);
                ActiveEvents.Instance.RaiseActiveEvent(
                    typeof(SmtpHelper),
                    "magix.cryptography._encrypt-mime-entity",
                    encryptNode);
                body = encryptNode["mime-entity"].Get<MimeEntity>();
            }
            return body;
        }
예제 #6
0
		void Render (MimeEntity entity)
		{
			var related = entity as MultipartRelated;
			if (related != null) {
				if (related.Root != null)
					Render (related);
				return;
			}

			var multipart = entity as Multipart;
			TextPart text;

			if (multipart != null) {
				if (multipart.ContentType.Matches ("multipart", "alternative")) {
					// A multipart/alternative is just a collection of alternate views.
					// The last part is the part that most closely matches what the
					// user saw in his or her email client's WYSIWYG editor.
					TextPart preferred = null;

					for (int i = multipart.Count; i > 0; i--) {
						related = multipart[i - 1] as MultipartRelated;

						if (related != null) {
							var root = related.Root;

							if (root != null && root.ContentType.Matches ("text", "html")) {
								Render (related);
								return;
							}

							continue;
						}

						text = multipart[i - 1] as TextPart;

						if (text == null)
							continue;

						if (text.ContentType.Matches ("text", "html")) {
							preferred = text;
							break;
						}

						if (preferred == null)
							preferred = text;
					}

					if (preferred != null)
						Render (preferred);
				} else if (multipart.Count > 0) {
					// The main message body is usually the first part of a multipart/mixed.
					Render (multipart[0]);
				}

				return;
			}

			text = entity as TextPart;

			if (text != null)
				Render (text);
		}
예제 #7
0
        private string[] GetLinesFromAttachment(MimeEntity attachment)
        {
            byte[] buffer;
            using (MemoryStream stream = new MemoryStream())
            {
                ((MimePart) attachment).ContentObject.DecodeTo(stream);
                buffer = stream.GetBuffer();
            }

            string content = GetContentWithEncoding(buffer);
            return content.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
        }
예제 #8
0
		/// <summary>
		/// Dispatches the entity to one of the more specialized visit methods in this class.
		/// </summary>
		/// <remarks>
		/// Dispatches the entity to one of the more specialized visit methods in this class.
		/// </remarks>
		/// <param name="entity">The MIME entity.</param>
		public virtual void Visit (MimeEntity entity)
		{
			if (entity != null)
				entity.Accept (this);
		}
예제 #9
0
		static IEnumerable<MimeEntity> EnumerateMimeParts (MimeEntity entity)
		{
			if (entity == null)
				yield break;

			var multipart = entity as Multipart;

			if (multipart != null) {
				foreach (var subpart in multipart) {
					foreach (var part in EnumerateMimeParts (subpart))
						yield return part;
				}

				yield break;
			}

			yield return entity;
		}
 /*
  * tries to sign and encrypt a MimeEntity
  */
 public static MimeEntity SignAndEncryptEntity(MimeEntity entity, MailboxAddress signer, IEnumerable<MailboxAddress> list)
 {
     using (WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(sys.StoreLocation.CurrentUser))
     {
         return ApplicationPkcs7Mime.SignAndEncrypt(ctx, signer, DigestAlgorithm.Sha1, list, entity);
     }
 }
예제 #11
0
        static void AddBodyPart(MailMessage message, MimeEntity entity)
        {
            if (entity is MessagePart) {
                // FIXME: how should this be converted into a MailMessage?
            } else if (entity is Multipart) {
                var multipart = (Multipart) entity;

                if (multipart.ContentType.Matches ("multipart", "alternative")) {
                    foreach (var part in multipart.OfType<MimePart> ()) {
                        // clone the content
                        var content = new MemoryStream ();
                        part.ContentObject.DecodeTo (content);
                        content.Position = 0;

                        var view = new AlternateView (content, GetContentType (part.ContentType));
                        view.TransferEncoding = GetTransferEncoding (part.ContentTransferEncoding);
                        if (!string.IsNullOrEmpty (part.ContentId))
                            view.ContentId = part.ContentId;

                        message.AlternateViews.Add (view);
                    }
                } else {
                    foreach (var part in multipart)
                        AddBodyPart (message, part);
                }
            } else {
                var part = (MimePart) entity;

                if (part.IsAttachment || !string.IsNullOrEmpty (message.Body) || !(part is TextPart)) {
                    // clone the content
                    var content = new MemoryStream ();
                    part.ContentObject.DecodeTo (content);
                    content.Position = 0;

                    var attachment = new Attachment (content, GetContentType (part.ContentType));

                    if (part.ContentDisposition != null) {
                        attachment.ContentDisposition.DispositionType = part.ContentDisposition.Disposition;
                        foreach (var param in part.ContentDisposition.Parameters)
                            attachment.ContentDisposition.Parameters.Add (param.Name, param.Value);
                    }

                    attachment.TransferEncoding = GetTransferEncoding (part.ContentTransferEncoding);

                    if (!string.IsNullOrEmpty (part.ContentId))
                        attachment.ContentId = part.ContentId;

                    message.Attachments.Add (attachment);
                } else {
                    message.IsBodyHtml = part.ContentType.Matches ("text", "html");
                    message.Body = ((TextPart) part).Text;
                }
            }
        }
예제 #12
0
 /// <summary>
 /// Visit the abstract MIME entity.
 /// </summary>
 /// <remarks>
 /// Visits the abstract MIME entity.
 /// </remarks>
 /// <param name="entity">The MIME entity.</param>
 protected internal virtual void VisitMimeEntity(MimeEntity entity)
 {
 }
예제 #13
0
 public MimeNode(MimeEntity entity, bool indexed)
 {
     Entity  = entity;
     Indexed = indexed;
 }
예제 #14
0
        /// <summary>
        /// Construct the message body based on the text-based bodies, the linked resources, and the attachments.
        /// </summary>
        /// <remarks>
        /// Combines the <see cref="Attachments"/>, <see cref="LinkedResources"/>, <see cref="TextBody"/>,
        /// and <see cref="HtmlBody"/> into the proper MIME structure suitable for display in many common
        /// mail clients.
        /// </remarks>
        /// <example>
        /// <code language="c#" source="Examples\BodyBuilder.cs" region="Complex" />
        /// </example>
        /// <returns>The message body.</returns>
        public MimeEntity ToMessageBody()
        {
            MultipartAlternative alternative = null;
            MimeEntity           body        = null;

            if (TextBody != null)
            {
                var text = new TextPart("plain");
                text.Text = TextBody;

                if (HtmlBody != null)
                {
                    alternative = new MultipartAlternative();
                    alternative.Add(text);
                    body = alternative;
                }
                else
                {
                    body = text;
                }
            }

            if (HtmlBody != null)
            {
                var        text = new TextPart("html");
                MimeEntity html;

                text.ContentId = MimeUtils.GenerateMessageId();
                text.Text      = HtmlBody;

                if (LinkedResources.Count > 0)
                {
                    var related = new MultipartRelated {
                        Root = text
                    };

                    foreach (var resource in LinkedResources)
                    {
                        related.Add(resource);
                    }

                    html = related;
                }
                else
                {
                    html = text;
                }

                if (alternative != null)
                {
                    alternative.Add(html);
                }
                else
                {
                    body = html;
                }
            }

            if (Attachments.Count > 0)
            {
                if (body == null && Attachments.Count == 1)
                {
                    return(Attachments[0]);
                }

                var mixed = new Multipart("mixed");

                if (body != null)
                {
                    mixed.Add(body);
                }

                foreach (var attachment in Attachments)
                {
                    mixed.Add(attachment);
                }

                body = mixed;
            }

            return(body ?? new TextPart("plain")
            {
                Text = string.Empty
            });
        }
		void Render (MimeEntity entity)
		{
			var related = entity as MultipartRelated;

			if (related != null) {
				RenderMultipartRelated (related);
				return;
			}

			var multipart = entity as Multipart;
			var text = entity as TextPart;

			// check if the entity is a multipart
			if (multipart != null) {
				if (multipart.ContentType.IsMimeType ("multipart", "alternative")) {
					// A multipart/alternative is just a collection of alternate views.
					// The last part is the format that most closely matches what the
					// user saw in his or her email client's WYSIWYG editor.
					TextPart preferred = null;

					for (int i = multipart.Count; i > 0; i--) {
						related = multipart[i - 1] as MultipartRelated;

						if (related != null) {
							var root = related.Root;

							if (root != null && root.ContentType.IsMimeType ("text", "html")) {
								RenderMultipartRelated (related);
								return;
							}

							continue;
						}

						text = multipart[i - 1] as TextPart;

						if (text == null)
							continue;

						if (text.IsHtml) {
							// we prefer html over plain text
							preferred = text;
							break;
						}

						if (preferred == null) {
							// we'll take what we can get
							preferred = text;
						}
					}

					if (preferred != null)
						RenderText (preferred);
				} else if (multipart.Count > 0) {
					// At this point we know we're not dealing with a multipart/related or a
					// multipart/alternative, so we can safely treat this as a multipart/mixed
					// even if it's not.

					// The main message body is usually the first part of a multipart/mixed. I
					// suppose that it might be better to render the first text/* part instead
					// (in case it's not the first part), but that's rare and probably also
					// indicates that the text is meant to be displayed between the other parts
					// (probably images or video?) in some sort of pseudo-multimedia "document"
					// layout. Modern clients don't do this, they use HTML or RTF instead.
					Render (multipart[0]);
				}
			} else if (text != null) {
				// render the text part
				RenderText (text);
			} else {
				// message/rfc822 part
			}
		}
 /*
  * tries to encrypt a MimeEntity
  */
 public static MimeEntity EncryptEntity(MimeEntity entity, IEnumerable<MailboxAddress> list)
 {
     using (WindowsSecureMimeContext ctx = new WindowsSecureMimeContext(sys.StoreLocation.CurrentUser))
     {
         return ApplicationPkcs7Mime.Encrypt(ctx, list, entity);
     }
 }
예제 #17
0
 public MessagePart(int id, MimeEntity messagePart)
 {
     Id = id;
     Headers = messagePart.Headers.ToDictionary(h => h.Field, h => h.Value);
 }
예제 #18
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MimeKit.MimeMessage"/> class.
		/// </summary>
		/// <remarks>
		/// Creates a new MIME message, specifying details at creation time.
		/// </remarks>
		/// <param name="from">The list of addresses in the From header.</param>
		/// <param name="to">The list of addresses in the To header.</param>
		/// <param name="subject">The subject of the message.</param>
		/// <param name="body">The body of the message.</param>
		public MimeMessage (IEnumerable<InternetAddress> from, IEnumerable<InternetAddress> to, string subject, MimeEntity body) : this ()
		{
			From.AddRange (from);
			To.AddRange (to);
			Subject = subject;
			Body = body;
		}
예제 #19
0
		void Push (MimeEntity entity)
		{
			var multipart = entity as Multipart;

			if (body == null) {
				body = entity;
			} else {
				var parent = stack.Peek ();
				parent.Add (entity);
			}

			if (multipart != null)
				stack.Push (multipart);
		}
예제 #20
0
		/// <summary>
		/// Visit the abstract MIME entity.
		/// </summary>
		/// <remarks>
		/// Visits the abstract MIME entity.
		/// </remarks>
		/// <param name="entity">The MIME entity.</param>
		protected internal virtual void VisitMimeEntity (MimeEntity entity)
		{
		}
예제 #21
0
		static IEnumerable<MimePart> EnumerateMimeParts (MimeEntity entity)
		{
			if (entity == null)
				yield break;

			var multipart = entity as Multipart;

			if (multipart != null) {
				foreach (var subpart in multipart) {
					foreach (var part in EnumerateMimeParts (subpart))
						yield return part;
				}

				yield break;
			}

			var msgpart = entity as MessagePart;

			if (msgpart != null) {
				var message = msgpart.Message;

				foreach (var part in EnumerateMimeParts (message.Body))
					yield return part;

				yield break;
			}

			yield return (MimePart) entity;
		}
예제 #22
0
        SmtpExtension PrepareMimeEntity(MimeEntity entity)
        {
            if (entity is MessagePart) {
                var message = ((MessagePart) entity).Message;
                return PrepareMimeEntity (message);
            }

            if (entity is Multipart) {
                var extensions = SmtpExtension.None;
                var multipart = (Multipart) entity;

                foreach (var child in multipart)
                    extensions |= PrepareMimeEntity (child);

                return extensions;
            }

            switch (GetFinalEncoding ((MimePart) entity)) {
            case ContentEncoding.EightBit:
                // if the server supports the 8BITMIME extension, use it...
                if ((capabilities & SmtpCapabilities.EightBitMime) != 0)
                    return SmtpExtension.EightBitMime;

                return SmtpExtension.BinaryMime;
            case ContentEncoding.Binary:
                return SmtpExtension.BinaryMime;
            default:
                return SmtpExtension.None;
            }
        }
예제 #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MimeKit.MimeMessage"/> class.
        /// <param name="args">An array of initialization parameters: headers and message parts.</param>
        /// </summary>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="args"/> is <c>null</c>.
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// <para><paramref name="args"/> contains more than one <see cref="MimeKit.MimeEntity"/>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="args"/> contains one or more arguments of an unknown type.</para>
        /// </exception>
        public MimeMessage(params object[] args) : this(ParserOptions.Default.Clone())
        {
            if (args == null)
            {
                throw new ArgumentNullException("args");
            }

            MimeEntity body = null;

            foreach (object obj in args)
            {
                if (obj == null)
                {
                    continue;
                }

                // Just add the headers and let the events (already setup) keep the
                // addresses in sync.

                var header = obj as Header;
                if (header != null)
                {
                    if (!header.Field.StartsWith("Content-", StringComparison.OrdinalIgnoreCase))
                    {
                        Headers.Add(header);
                    }

                    continue;
                }

                var headers = obj as IEnumerable <Header>;
                if (headers != null)
                {
                    foreach (var h in headers)
                    {
                        if (!h.Field.StartsWith("Content-", StringComparison.OrdinalIgnoreCase))
                        {
                            Headers.Add(h);
                        }
                    }

                    continue;
                }

                var entity = obj as MimeEntity;
                if (entity != null)
                {
                    if (body != null)
                    {
                        throw new ArgumentException("Message body should not be specified more than once.");
                    }

                    body = entity;
                    continue;
                }

                throw new ArgumentException("Unknown initialization parameter: " + obj.GetType());
            }

            if (body != null)
            {
                Body = body;
            }

            // Do exactly as in the parameterless constructor but avoid setting a default
            // value if an header already provided one.

            if (!Headers.Contains("From"))
            {
                Headers["From"] = string.Empty;
            }
            if (!Headers.Contains("To"))
            {
                Headers["To"] = string.Empty;
            }
            if (date == default(DateTimeOffset))
            {
                Date = DateTimeOffset.Now;
            }
            if (!Headers.Contains("Subject"))
            {
                Subject = string.Empty;
            }
        }