/// <summary>
 /// Generate and add a MimePart to the embedded objects collection, using the specified file.
 /// </summary>
 /// <param name="path">The file containing the MimePart's content.</param>
 /// <param name="contentId">The Content-ID Header field will be used for the part.</param>
 /// <param name="charset">The charset of the text contained in the file.</param>
 public virtual string Add(string path, string contentId, string charset)
 {
     MimePart part = new MimePart(path, contentId, charset);
     part.ContentDisposition.Disposition = "inline";
     this.List.Add(part);
     return part.EmbeddedObjectContentId;
 }
 /// <summary>
 /// Generate and add a MimePart to the embedded objects collection, using the specified file.
 /// </summary>
 /// <param name="path">The file containing the MimePart's content.</param>
 /// <param name="generateContentId">If true, a Content-ID Header field will be generated for the part.</param>
 public new string Add(string path, bool generateContentId)
 {
     MimePart part = new MimePart(path, generateContentId);
     part.ContentDisposition.Disposition = "inline";
     this.List.Add(part);
     return part.EmbeddedObjectContentId;
 }
        internal static Message MapOutboxToMailMessage(IDataRecord dr)
        {
            Encoding encoding = Codec.GetEncoding("iso-8859-1");

            ActiveUp.Net.Mail.Message msg = new ActiveUp.Net.Mail.Message();
            msg.Charset = encoding.BodyName;
            msg.ContentTransferEncoding = ContentTransferEncoding.QuotedPrintable;
            msg.ContentType             = new ContentType();
            string appo = null;

            if (!String.IsNullOrEmpty(appo = dr.GetString("MAIL_CCN")))
            {
                msg.Bcc = Parser.ParseAddresses(appo);
                appo    = null;
            }
            if (!String.IsNullOrEmpty(appo = dr.GetString("MAIL_CC")))
            {
                msg.Cc = Parser.ParseAddresses(appo);
                appo   = null;
            }
            if (!String.IsNullOrEmpty(appo = dr.GetString("MAIL_TO")))
            {
                msg.To = Parser.ParseAddresses(appo);
                appo   = null;
            }
            if (!String.IsNullOrEmpty(appo = dr.GetString("MAIL_TEXT")))
            {
                msg.BodyHtml      = new ActiveUp.Net.Mail.MimeBody(ActiveUp.Net.Mail.BodyFormat.Html);
                msg.BodyHtml.Text = appo;
                appo = null;
            }
            msg.From    = Parser.ParseAddress(dr.GetString("MAIL_SENDER"));
            msg.Id      = (int)dr.GetInt64("ID_MAIL");
            msg.Subject = dr.GetString("MAIL_SUBJECT");

            if (!String.IsNullOrEmpty(appo = dr.GetString("ALLEG")))
            {
                var mime = appo.Split(new char[] { ';' }).Select(x =>
                {
                    ActiveUp.Net.Mail.MimePart mp = new ActiveUp.Net.Mail.MimePart();
                    string[] pp      = x.Split('#');
                    mp.ContentId     = pp[0];
                    mp.Filename      = pp[1];
                    mp.ParentMessage = msg;
                    return(mp);
                });
                foreach (var mm in mime)
                {
                    msg.Attachments.Add(mm);
                }
            }
            return(msg);
        }
Exemple #4
0
        /// <summary>
        /// Parses the sub parts.
        /// </summary>
        /// <param name="part">The part.</param>
        private static void ParseSubParts(ref MimePart part, Message message)
        {
            string boundary = part.ContentType.Parameters["boundary"];

            ActiveUp.Net.Mail.Logger.AddEntry("boundary : " + boundary);
            string[] arrpart = Regex.Split(part.OriginalContent, @"\r?\n?" + Regex.Escape("--" + boundary));
            for (int i = 1; i < arrpart.Length - 1; i++)
            {
                string strpart = arrpart[i];
                if (!strpart.StartsWith("--") && !string.IsNullOrEmpty(strpart))
                {
                    MimePart newpart = Parser.ParseMimePart(strpart, message);
                    newpart.ParentMessage = message;
                    newpart.Container     = part;
                    part.SubParts.Add(newpart);
                }
            }
        }
Exemple #5
0
        public static MimePart GetSignaturePart(SignedCms cms)
        {
            if (!cms.Detached)
            {
                throw new ArgumentException("The CMS object is not a detached signature.");
            }

            var part = new MimePart();

            part.ContentType.MimeType = "application/x-pkcs7-signature";
            part.ContentType.Parameters.Add("name", "\"smime.p7s\"");
            part.ContentTransferEncoding        = ContentTransferEncoding.Base64;
            part.ContentDisposition.Disposition = "attachment";
            part.ContentDisposition.FileName    = "smime.p7s";

            part.BinaryContent = cms.Encode();

            return(part);
        }
Exemple #6
0
        public void CheckAndFixName(MimePart part)
        {
            string new_name = "attachment";

            if (string.IsNullOrEmpty(part.ContentDisposition.FileName))
            {
                part.ContentDisposition.FileName = "attachment";
            }
            else if (part.Filename.Length > 255)
            {
                var long_name = string.IsNullOrEmpty(part.Filename) ? part.Filename : "attachment";

                try
                {
                    var name = Path.GetFileName(long_name);

                    if (!string.IsNullOrEmpty(name) && new_name.Length < 250)
                    {
                        new_name = name;
                    }
                }
                catch (Exception)
                {
                }
            }
            else
            {
                return;
            }

            var extension_by_type = !string.IsNullOrEmpty(part.ContentType.MimeType) ?
                                    MimeTypesHelper.GetImageExtensionByMimeqType(part.ContentType.MimeType) :
                                    "ext";

            new_name = Path.ChangeExtension(new_name,
                                            string.IsNullOrEmpty(extension_by_type) ? "ext" : extension_by_type);

            part.ContentDisposition.FileName = new_name;
            part.ContentName = new_name;
            part.Filename    = new_name;
        }
Exemple #7
0
        private static void ParseHeaderFields(MimePart part, int headerEnd)
        {
            string header = Unfold(part.OriginalContent.Substring(0, headerEnd));
            Match  m      = Regex.Match(header, @"(?<=((\r?\n)|\n)|\A)\S+:(.|(\r?\n[\t ]))+(?=((\r?\n)\S)|\Z)");

            while (m.Success)
            {
                if (m.Value.ToLower().StartsWith("content-type:"))
                {
                    part.ContentType = GetContentType(m.Value);
                }
                else if (m.Value.ToLower().StartsWith("content-disposition:"))
                {
                    part.ContentDisposition = GetContentDisposition(m.Value);
                }

                part.HeaderFields.Add(FormatFieldName(m.Value.Substring(0, m.Value.IndexOf(':'))), Codec.RFC2047Decode(m.Value.Substring(m.Value.IndexOf(':') + 1).Trim(' ', '\r', '\n')));
                part.HeaderFieldNames.Add(FormatFieldName(m.Value.Substring(0, m.Value.IndexOf(':'))), Codec.RFC2047Decode(m.Value.Substring(0, m.Value.IndexOf(':')).Trim(' ', '\r', '\n')));
                m = m.NextMatch();
            }
        }
Exemple #8
0
        private static MimePart CreateAttachment(int tennantid, MailAttachment attachment, bool loadAttachments)
        {
            ActiveUp.Net.Mail.MimePart retVal = new ActiveUp.Net.Mail.MimePart();
            var fileName = Path.GetFileName(HttpUtility.UrlDecode(attachment.Url.Split('|')[1]));

            if (loadAttachments)
            {
                var pathInfo = attachment.Url.Split('|');

                var is_embedded = !string.IsNullOrEmpty(attachment.ContentID);

                using (var s = is_embedded ?
                               GetDataStoreForEmbeddedAttachments(tennantid).GetReadStream(EmbeddedDomain, pathInfo[1]) :
                               GetDataStoreForAttachments(tennantid, pathInfo[0]).GetReadStream(HttpUtility.UrlDecode(pathInfo[1])))
                {
                    retVal = new MimePart(s.GetCorrectBuffer(), fileName);
                    retVal.ContentDisposition.Disposition = "attachment";
                }
                if (attachment.ContentID != null)
                {
                    retVal.ContentId = attachment.ContentID;
                }
            }
            else
            {
                var conentType = ASC.Common.Web.MimeMapping.GetMimeMapping(attachment.Url);
                retVal.ContentType = new ActiveUp.Net.Mail.ContentType()
                {
                    Type = conentType
                };
                retVal.Filename = Path.GetFileName(HttpUtility.UrlDecode(fileName));
                if (attachment.ContentID != null)
                {
                    retVal.ContentId = attachment.ContentID;
                }
                retVal.TextContent = "";
            }

            return(retVal);
        }
Exemple #9
0
        public MimePart ToMimePart()
        {
            MimePart part = new MimePart();

            if (this.Format.Equals(BodyFormat.Text))
            {
                part.ContentType.MimeType = "text/plain";
            }
            else if (this.Format.Equals(BodyFormat.Html))
            {
                part.ContentType.MimeType = "text/html";
            }

            part.ContentType.Parameters.Add("charset", this.Charset);

            part.Charset = this.Charset;

            part.ContentTransferEncoding = this.ContentTransferEncoding;

            string content = this.Text;

            /*if (this.ContentTransferEncoding.Equals(ContentTransferEncoding.Base64))
             * {
             *  byte[] contentBytes = Encoding.GetEncoding(this.Charset).GetBytes(this.Text);
             *  content = Convert.ToBase64String(contentBytes);
             * }
             * else if (this.ContentTransferEncoding.Equals(ContentTransferEncoding.QuotedPrintable))
             * {
             *  content = Codec.ToQuotedPrintable(this.Text, this.Charset);
             * }
             * else content = this.Text;*/

            part.TextContent = content;

            return(part);
        }
Exemple #10
0
        /// <summary>
        /// Parses the message.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public static Message ParseMessage(byte[] data)
        {
            Message message = new Message();

            try
            {
                // Build a part tree and get all headers.
                MimePart part = ParseMimePart(data, message);

                // Fill a new message object with the new information.
                message.OriginalData     = data;
                message.HeaderFields     = part.HeaderFields;
                message.HeaderFieldNames = part.HeaderFieldNames;

                // Dispatch header fields to corresponding object.
                foreach (string key in message.HeaderFields.AllKeys)
                {
                    string value = message.HeaderFields[key];
                    if (key.Equals("received"))
                    {
                        Match m = Regex.Match(value, @"from.+?(?=(from|$))");
                        while (m.Success)
                        {
                            message.Trace.Add(ParseTrace(key + ": " + m.Value));
                            m = m.NextMatch();
                        }
                    }
                    else if (key.Equals("to"))
                    {
                        message.To = ParseAddresses(value);
                    }
                    else if (key.Equals("cc"))
                    {
                        message.Cc = ParseAddresses(value);
                    }
                    else if (key.Equals("bcc"))
                    {
                        message.Bcc = ParseAddresses(value);
                    }
                    else if (key.Equals("reply-to"))
                    {
                        message.ReplyTo = ParseAddress(value);
                    }
                    else if (key.Equals("from"))
                    {
                        message.From = ParseAddress(value);
                    }
                    else if (key.Equals("sender"))
                    {
                        message.Sender = ParseAddress(value);
                    }
                    else if (key.Equals("content-type"))
                    {
                        message.ContentType = GetContentType(key + ": " + value);
                    }
                    else if (key.Equals("content-disposition"))
                    {
                        message.ContentDisposition = GetContentDisposition(key + ": " + value);
                    }
                    else if (key.Equals("domainkey-signature"))
                    {
                        message.Signatures.DomainKeys = Signature.Parse(key + ": " + value, message);
                    }
                }

                if (message.ContentType.MimeType.Equals("application/pkcs7-mime") || message.ContentType.MimeType.Equals("application/x-pkcs7-mime"))
                {
                    if (message.ContentType.Parameters["smime-type"] != null && message.ContentType.Parameters["smime-type"].Equals("enveloped-data"))
                    {
                        message.IsSmimeEncrypted = true;
                    }
                    if (message.ContentType.Parameters["smime-type"] != null && message.ContentType.Parameters["smime-type"].Equals("signed-data"))
                    {
                        message.HasSmimeSignature = true;
                    }
                }

                if (message.ContentType.MimeType.Equals("multipart/signed"))
                {
                    message.HasSmimeDetachedSignature = true;
                }

                // Keep a reference to the part tree within the new Message object.
                message.PartTreeRoot = part;

                DispatchParts(ref message);

                // Dispatch the part tree content to the appropriate collections and properties.
                // TODO
            }
            catch (Exception ex)
            {
                if (ErrorParsing != null)
                {
                    ErrorParsing(null, ex);
                }
            }
            return(message);
        }
Exemple #11
0
        /// <summary>
        /// Process message Part loaded to complete Message.
        /// </summary>
        /// <param name="part">Loaded part from EML.</param>
        /// <param name="message">Final message.</param>
        private static void DispatchPart(MimePart part, ref Message message)
        {
            // This is a container part.
            if (part.SubParts.Count > 0)
            {
                DispatchParts(part, ref message);
            }
            // This is a leaf part.
            else
            {
                bool added = false;
                // If this part has to be displayed has an attachment, add it to the appropriate collection.
                if (part.ContentDisposition.Disposition.Equals("attachment"))
                {
                    message.Attachments.Add(part);
                    added = true;
                }
                // If this part has to be displayed at the same time as the main body, add it to the appropriate collection.
                else if (part.ContentDisposition.Disposition.Equals("inline"))
                {
                    message.EmbeddedObjects.Add(part);
                    added = true;
                }
                // Other parts are miscellaneous. How they are to be displayed is at the end-user's discretion.
                // Fix for avoid attach original mail message
                else if (!message.BodyText.ToMimePart().ContentTransferEncoding.Equals(part.ContentTransferEncoding))
                {
                    message.UnknownDispositionMimeParts.Add(part);
                    added = true;
                }

                // We will consider the highest-level text parts that are not attachments to be the intended for display.
                // We know the highest-level parts will be set, because the parser first goes to the deepest level and returns top-level parts last.
                if (part.ContentType.Type.ToLower().Equals("text") && !part.ContentDisposition.Disposition.ToLower().Equals("attachment"))
                {
                    if (part.ContentType.SubType.ToLower().Equals("plain"))
                    {
                        if (part.ContentDisposition.Disposition.ToLower() == "inline")
                        {
                            message.BodyText.Text += part.TextContent;
                        }
                        else
                        {
                            message.BodyText.Charset = part.Charset;
                            message.BodyText.Text    = part.TextContent;
                        }
                    }
                    else if (part.ContentType.SubType.ToLower().Equals("html"))
                    {
                        if (part.ContentDisposition.Disposition.ToLower() == "inline")
                        {
                            message.IsHtml         = true;
                            message.BodyHtml.Text += part.TextContent;
                        }
                        else
                        {
                            message.IsHtml           = true;
                            message.BodyHtml.Charset = part.Charset;
                            message.BodyHtml.Text    = part.TextContent;
                        }
                    }
                    else if (part.ContentType.SubType.ToLower().Equals("xml") && !added)
                    {
                        message.Attachments.Add(part);
                    }
                }
                // Parse message/rfc822 parts as Message objects and place them in the appropriate collection.
                if (part.ContentType.MimeType.ToLower().Equals("message/rfc822"))
                {
                    message.SubMessages.Add(ParseMessage(part.BinaryContent));
                }

                if (part.ContentType.MimeType.ToLower().Equals("application/pkcs7-signature") || part.ContentType.MimeType.ToLower().Equals("application/x-pkcs7-signature"))
                {
                    string toDigest = part.Container.TextContent;
                    toDigest = Regex.Split(toDigest, "\r\n--" + part.Container.ContentType.Parameters["boundary"])[1];
                    toDigest = toDigest.TrimStart('\r', '\n');

                    //TODO: What should be done in PPC ?
#if !PocketPC
                    message.Signatures.Smime = new SignedCms(new ContentInfo(Encoding.ASCII.GetBytes(toDigest)), true);
                    message.Signatures.Smime.Decode(part.BinaryContent);
#endif
                }

                // Anyway, this is a leaf part of the message.
                message.LeafMimeParts.Add(part);
            }
        }
Exemple #12
0
        /// <summary>
        /// Decodes the part body.
        /// </summary>
        /// <param name="part">The part.</param>
        private static void DecodePartBody(ref MimePart part)
        {
            // Let's see if a charset is specified. Otherwise we default to "iso-8859-1".
            string charset = (!string.IsNullOrEmpty(part.Charset) ? part.Charset : "iso-8859-1");

#if PocketPC
            if (charset.ToLower() == "iso-8859-1")
                charset = "windows-1252";
#endif
            // This is a Base64 encoded part body.
            if (part.ContentTransferEncoding.Equals(ContentTransferEncoding.Base64))
            {
#if !PocketPC
                try
                {
#endif
                    //We have the Base64 string so we can decode it.
                    part.BinaryContent = Convert.FromBase64String(part.TextContent);
#if !PocketPC
                }
                 catch (System.FormatException)
                {
                    part.TextContent = part.TextContent.Remove(part.TextContent.LastIndexOf("=")+1);
                    part.BinaryContent = Convert.FromBase64String(part.TextContent);
                }
#endif

                if (part.ContentDisposition != ContentDisposition.Attachment)
                    part.TextContent = System.Text.Encoding.GetEncoding(charset).GetString(part.BinaryContent,0,part.BinaryContent.Length);
            }
            // This is a quoted-printable encoded part body.
            else if (part.ContentTransferEncoding.Equals(ContentTransferEncoding.QuotedPrintable))
            {
                //else if (part.Container != null && part.Container.Charset != null && part.Container.Charset.Length > 0)
                //    charset = part.Container.Charset;

                // Let's decode.
                part.TextContent = Codec.FromQuotedPrintable(part.TextContent, charset);
                // Knowing the charset, we can provide a binary version of this body data.
                part.BinaryContent = Encoding.GetEncoding(charset).GetBytes(part.TextContent);
            }
            // Otherwise, this is an unencoded part body and we keep the text version as it is.
            else
            {
                var encoding = Encoding.GetEncoding(charset);
                // Knowing the charset, we can provide a binary version of this body data.
                part.BinaryContent = encoding.GetBytes(part.TextContent);
                part.TextContent = encoding.GetString(part.BinaryContent);
            }
        }
Exemple #13
0
 /// <summary>
 /// Dispatches the parts.
 /// </summary>
 /// <param name="root">The root.</param>
 /// <param name="message">The message.</param>
 private static void DispatchParts(MimePart root, ref Message message)
 {
     foreach (MimePart entity in root.SubParts)
     {
         DispatchPart(entity, ref message);
     }
 }
 /// <summary>
 /// Adds the MimePart object to the collection.
 /// </summary>
 /// <param name="part">The MimePart to be added.</param>
 public void Add(MimePart part)
 {
     this.List.Add(part);
 }
Exemple #15
0
        /// <summary>
        /// Parses the MIME part.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public static MimePart ParseMimePart(string data, Message message)
        {
            MimePart part = new MimePart();

            part.ParentMessage   = message;
            part.OriginalContent = data;

            try
            {
                // Separate header and body.
                int headerEnd = Regex.Match(data, @".(?=\r?\n\r?\n)").Index + 1;
                int bodyStart = Regex.Match(data, @"(?<=\r?\n\r?\n).").Index;

                //TODO: remove this workaround
                if (bodyStart == 0)
                {
                    //bodyStart = data.IndexOf("\r\n\r\n");
                    // Fix for a bug - the bodyStart was -1 (Invalid), MCALADO: 04/07/2008
                    int indexBody = data.IndexOf("\r\n\r\n");
                    if (indexBody > 0)
                    {
                        bodyStart = indexBody;
                    }
                }
                if (data.Length >= headerEnd)
                {
                    string header = data.Substring(0, headerEnd);

                    header = Parser.Unfold(header);
                    //header = header);

                    // The bodyStart need to be greather than data.length - MCALADO: 04/07/2008
                    string body = string.Empty;
                    if (bodyStart < data.Length)
                    {
                        body = data.Substring(bodyStart);
                    }

                    // Store the (maybe still encoded) body.
                    part.TextContent = body;



                    // Parse header fields and their parameters.
                    Match m = Regex.Match(header, @"(?<=((\r?\n)|\n)|\A)\S+:(.|(\r?\n[\t ]))+(?=((\r?\n)\S)|\Z)");
                    while (m.Success)
                    {
                        if (m.Value.ToLower().StartsWith("content-type:"))
                        {
                            part.ContentType = Parser.GetContentType(m.Value);
                        }
                        else if (m.Value.ToLower().StartsWith("content-disposition:"))
                        {
                            part.ContentDisposition = Parser.GetContentDisposition(m.Value);
                        }
                        part.HeaderFields.Add(FormatFieldName(m.Value.Substring(0, m.Value.IndexOf(':'))), Codec.RFC2047Decode(m.Value.Substring(m.Value.IndexOf(':') + 1).Trim(' ', '\r', '\n')));
                        part.HeaderFieldNames.Add(FormatFieldName(m.Value.Substring(0, m.Value.IndexOf(':'))), Codec.RFC2047Decode(m.Value.Substring(0, m.Value.IndexOf(':')).Trim(' ', '\r', '\n')));
                        m = m.NextMatch();
                    }

                    // Build the part tree.

                    // This is a container part.
                    if (part.ContentType.Type.ToLower().Equals("multipart"))
                    {
                        Parser.ParseSubParts(ref part, message);
                    }
                    // This is a nested message.
                    else if (part.ContentType.Type.ToLower().Equals("message"))
                    {
                        // TODO
                    }
                    // This is a leaf of the part tree
                    // Check necessary for single part emails (fix from alex294 on CodePlex)
                    // Why would we consider the body only to the first string?  Doesn't make sense - and fails
                    //else if (part.ContentType.Type.ToLower().Equals("text"))
                    //{
                    //    int BodyEnd = body.IndexOf(' ');
                    //    if (BodyEnd > 0)
                    //    {
                    //        part.TextContent = body.Substring(0, BodyEnd);
                    //    }
                    //}

                    DecodePartBody(ref part);

                    try
                    {
                        BodyParsed(null, message);
                    }
                    catch (Exception)
                    {
                        // event is not supported.
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ParsingException(ex.Message);
            }

            return(part);
        }
		/// <summary>
		/// Adds the MimePart object to the collection.
		/// </summary>
		/// <param name="part">The MimePart to be added.</param>
		public void Add(MimePart part)
		{
			this.List.Add(part);
		}
 /// <summary>
 /// Generate and add a MimePart to the embedded objects collection, using the specified file.
 /// </summary>
 /// <param name="path">The file containing the MimePart's content.</param>
 /// <param name="generateContentId">If true, a Content-ID Header field will be generated for the part.</param>
 /// <param name="charset">The charset of the text contained in the file.</param>
 /// <remarks>This method is to be used with text files to ensure data integrity using the correct charset.</remarks>
 public new string Add(string path, bool generateContentId, string charset)
 {
     MimePart part = new MimePart(path, generateContentId, charset);
     part.ContentDisposition.Disposition = "inline";
     this.List.Add(part);
     return part.ContentId;
 }
        private static MimePart CreateAttachment(int tennantid, MailAttachment attachment, bool loadAttachments)
        {
            ActiveUp.Net.Mail.MimePart retVal = new ActiveUp.Net.Mail.MimePart();
            var fileName = Path.GetFileName(HttpUtility.UrlDecode(attachment.Url.Split('|')[1]));

            if (loadAttachments)
            {
                var pathInfo = attachment.Url.Split('|');

                var is_embedded = !string.IsNullOrEmpty(attachment.ContentID);

                using (var s = is_embedded ?
                    GetDataStoreForEmbeddedAttachments(tennantid).GetReadStream(EmbeddedDomain, pathInfo[1]) :
                    GetDataStoreForAttachments(tennantid, pathInfo[0]).GetReadStream(HttpUtility.UrlDecode(pathInfo[1])))
                {
                    retVal = new MimePart(s.GetCorrectBuffer(), fileName);
                    retVal.ContentDisposition.Disposition = "attachment";
                }
                if (attachment.ContentID != null) retVal.ContentId = attachment.ContentID;
            }
            else
            {
                var conentType = ASC.Common.Web.MimeMapping.GetMimeMapping(attachment.Url);
                retVal.ContentType = new ActiveUp.Net.Mail.ContentType() { Type = conentType };
                retVal.Filename = Path.GetFileName(HttpUtility.UrlDecode(fileName));
                if (attachment.ContentID != null) retVal.ContentId = attachment.ContentID;
                retVal.TextContent = "";
            }

            return retVal;
        }
Exemple #19
0
 /// <summary>
 /// Add a MimePart to the embedded objects collection.
 /// </summary>
 /// <param name="part"></param>
 public new void Add(MimePart part)
 {
     part.ContentDisposition.Disposition = "inline";
     CheckAndFixName(part);
     this.List.Add(part);
 }
 /// <summary>
 /// Add a MimePart to the embedded objects collection.
 /// </summary>
 /// <param name="part"></param>
 public new void Add(MimePart part)
 {
     part.ContentDisposition.Disposition = "inline";
     CheckAndFixName(part);
     this.List.Add(part);
 }
        public void CheckAndFixName(MimePart part)
        {
            string new_name = "attachment";

            if (string.IsNullOrEmpty(part.ContentDisposition.FileName))
            {
                part.ContentDisposition.FileName = "attachment";
            }
            else if (part.Filename.Length > 255)
            {
                var long_name = string.IsNullOrEmpty(part.Filename) ? part.Filename : "attachment";

                try
                {
                    var name = Path.GetFileName(long_name);

                    if (!string.IsNullOrEmpty(name) && new_name.Length < 250)
                        new_name = name;
                }
                catch (Exception)
                {
                }
            }
            else
            {
                return;
            }

            var extension_by_type = !string.IsNullOrEmpty(part.ContentType.MimeType) ? 
                MimeTypesHelper.GetImageExtensionByMimeqType(part.ContentType.MimeType) :
                "ext";

            new_name = Path.ChangeExtension(new_name,
                                            string.IsNullOrEmpty(extension_by_type) ? "ext" : extension_by_type);

            part.ContentDisposition.FileName = new_name;
            part.ContentName = new_name;
            part.Filename = new_name;

        }
Exemple #22
0
        public MimePart ToMimePart()
        {
            MimePart part = new MimePart();

            if (this.Format.Equals(BodyFormat.Text)) part.ContentType.MimeType = "text/plain";
            else if (this.Format.Equals(BodyFormat.Html)) part.ContentType.MimeType = "text/html";

            part.ContentType.Parameters.Add("charset", this.Charset);

            part.ContentTransferEncoding = this.ContentTransferEncoding;

            /*string content = string.Empty;

            if (this.ContentTransferEncoding.Equals(ContentTransferEncoding.Base64))
            {
                byte[] contentBytes = Encoding.GetEncoding(this.Charset).GetBytes(this.Text);
                content = Convert.ToBase64String(contentBytes);
            }
            else if (this.ContentTransferEncoding.Equals(ContentTransferEncoding.QuotedPrintable))
            {
                content = Codec.ToQuotedPrintable(this.Text, this.Charset);
            }
            else content = this.Text;*/

            part.TextContent = this.Text;

            return part;
        }
Exemple #23
0
        /// <summary>
        /// Signs the message and envelopes it.
        /// </summary>
        /// <param name="signer">An object containing the signer's information.</param>
        /// <example>
        /// <code>
        /// [C#]
        /// 
        /// CmsSigner signer = new CmsSigner(new X509Certificate2("C:\\mycertificate.pfx"));
        /// 
        /// // Here we only want the signer's certificate to be sent along. Not the whole chain.
        /// signer.IncludeOption = X509IncludeOption.EndCertOnly;
        /// 
        /// message.SmimeEnvelopeAndSignBy(signer);
        /// </code>
        /// </example>
        public void SmimeEnvelopeAndSignBy(CmsSigner signer)
        {
            string mimeString = this.ToMimeString();
            byte[] tosign = Encoding.ASCII.GetBytes(mimeString);
            SignedCms cms = new SignedCms(new ContentInfo(tosign));
            cms.ComputeSignature(signer);

            MimePart envelope = new MimePart();

            envelope.ContentType.MimeType = "application/pkcs7-mime";
            envelope.ContentType.Parameters.Add("smime-type", "signed-data");
            envelope.ContentType.Parameters.Add("name", "smime.p7m");
            envelope.ContentDisposition.Disposition = "attachment";
            envelope.ContentDisposition.FileName = "smime.p7m";
            envelope.ContentTransferEncoding = ContentTransferEncoding.Base64;

            envelope.BinaryContent = cms.Encode();

            this.PartTreeRoot = envelope;

            this.ContentType = this.PartTreeRoot.ContentType;
            this.ContentDisposition = this.PartTreeRoot.ContentDisposition;
            this.ContentTransferEncoding = this.PartTreeRoot.ContentTransferEncoding;
        }
Exemple #24
0
        public static MimePart GetSignaturePart(SignedCms cms)
        {
            if (!cms.Detached) throw new ArgumentException("The CMS object is not a detached signature.");

            MimePart part = new MimePart();

            part.ContentType.MimeType = "application/x-pkcs7-signature";
            part.ContentType.Parameters.Add("name", "\"smime.p7s\"");
            part.ContentTransferEncoding = ContentTransferEncoding.Base64;
            part.ContentDisposition.Disposition = "attachment";
            part.ContentDisposition.FileName = "smime.p7s";

            part.BinaryContent = cms.Encode();

            return part;
        }
Exemple #25
0
 /// <summary>
 /// Adds the MimePart object to the collection.
 /// </summary>
 /// <param name="part">The MimePart to be added.</param>
 public void Add(MimePart part)
 {
     List.Add(part);
 }
Exemple #26
0
 public void Send(object sender, System.EventArgs e)
 {
     ActiveUp.Net.Mail.Message message = new ActiveUp.Net.Mail.Message();
     try
     {
         message.Subject = iSubject.Text;
         message.To      = ActiveUp.Net.Mail.Parser.ParseAddresses(iTo.Text);
         message.Cc      = ActiveUp.Net.Mail.Parser.ParseAddresses(iCc.Text);
         message.Bcc     = ActiveUp.Net.Mail.Parser.ParseAddresses(iBcc.Text);
         if (iReplyTo.Text.Length > 0)
         {
             message.ReplyTo = ActiveUp.Net.Mail.Parser.ParseAddresses(iReplyTo.Text)[0];
         }
         string   s1    = iBody.Text;
         string[] sArr1 = System.IO.Directory.GetFiles(Page.Server.MapPath(Application["writedirectory\uFFFD"].ToString()));
         for (int i1 = 0; i1 < sArr1.Length; i1++)
         {
             string s2 = sArr1[i1];
             if ((s2.IndexOf(Session.SessionID + "_Image_\uFFFD") != -1) && (s1.IndexOf(s2.Substring(s2.IndexOf(Session.SessionID))) != -1))
             {
                 ActiveUp.Net.Mail.MimePart embeddedObject1 = new ActiveUp.Net.Mail.MimePart(s2, true, string.Empty);
                 embeddedObject1.ContentName = s2.Substring(s2.IndexOf("_Image_\uFFFD") + 7);
                 message.EmbeddedObjects.Add(embeddedObject1);
                 s1 = s1.Replace("http://\uFFFD" + Request.ServerVariables["HTTP_HOST\uFFFD"] + Request.ServerVariables["URL\uFFFD"].Substring(0, Request.ServerVariables["URL\uFFFD"].LastIndexOf("/\uFFFD") + 1) + "temp\uFFFD" + s2.Substring(s2.LastIndexOf('\\')).Replace("\\\uFFFD", "/\uFFFD"), "cid:\uFFFD" + embeddedObject1.ContentId);
                 s1 = s1.Replace("temp\uFFFD" + s2.Substring(s2.LastIndexOf('\\')).Replace("\\\uFFFD", "/\uFFFD"), "cid:\uFFFD" + embeddedObject1.ContentId);
             }
         }
         string[] sArr3 = System.IO.Directory.GetFiles(Server.MapPath("icons/emoticons/\uFFFD"));
         for (int i2 = 0; i2 < sArr3.Length; i2++)
         {
             string s3 = sArr3[i2];
             if (s1.IndexOf("icons/emoticons\uFFFD" + s3.Substring(s3.LastIndexOf("\\\uFFFD")).Replace("\\\uFFFD", "/\uFFFD")) != -1)
             {
                 ActiveUp.Net.Mail.MimePart embeddedObject2 = new ActiveUp.Net.Mail.MimePart(s3, true, string.Empty);
                 embeddedObject2.ContentName = s3.Substring(s3.LastIndexOf("\\\uFFFD") + 1);
                 message.EmbeddedObjects.Add(embeddedObject2);
                 s1 = s1.Replace("http://\uFFFD" + Request.ServerVariables["HTTP_HOST\uFFFD"] + Request.ServerVariables["URL\uFFFD"].Substring(0, Request.ServerVariables["URL\uFFFD"].LastIndexOf("/\uFFFD") + 1) + "icons/emoticons\uFFFD" + s3.Substring(s3.LastIndexOf('\\')).Replace("\\\uFFFD", "/\uFFFD"), "cid:\uFFFD" + embeddedObject2.ContentId);
             }
         }
         message.BodyHtml.Text = s1;
         message.BodyText.Text = iBody.TextStripped;
         //message.Headers.Add("x-sender-ip\uFFFD", Request.ServerVariables["REMOTE_ADDR\uFFFD"]);
         string[] sArr5 = System.IO.Directory.GetFiles(Page.Server.MapPath(Application["writedirectory\uFFFD"].ToString()));
         for (int i3 = 0; i3 < sArr5.Length; i3++)
         {
             string s4 = sArr5[i3];
             if (s4.IndexOf("\\temp\\\uFFFD" + Session.SessionID + "_Attach_\uFFFD") != -1)
             {
                 ActiveUp.Net.Mail.MimePart attachment = new ActiveUp.Net.Mail.MimePart(s4, true);
                 attachment.Filename    = s4.Substring(s4.IndexOf("_Attach_\uFFFD") + 8);
                 attachment.ContentName = s4.Substring(s4.IndexOf("_Attach_\uFFFD") + 8);
                 message.Attachments.Add(attachment);
             }
         }
         message.From = new ActiveUp.Net.Mail.Address(iFromEmail.Text, iFromName.Text);
         if (((System.Web.UI.HtmlControls.HtmlInputButton)sender).ID == "iSubmit\uFFFD")
         {
             try
             {
                 message.Send((string)Application["smtpserver\uFFFD"], System.Convert.ToInt32(Application["smtpport\uFFFD"]), (string)Application["user\uFFFD"], (string)Application["password\uFFFD"], ActiveUp.Net.Mail.SaslMechanism.CramMd5);
             }
             catch
             {
                 try
                 {
                     message.Send((string)Application["smtpserver\uFFFD"], System.Convert.ToInt32(Application["smtpport\uFFFD"]), (string)Application["user\uFFFD"], (string)Application["password\uFFFD"], ActiveUp.Net.Mail.SaslMechanism.CramMd5);
                 }
                 catch
                 {
                     message.Send((string)Application["smtpserver\uFFFD"], System.Convert.ToInt32(Application["smtpport\uFFFD"]));
                 }
             }
             try
             {
                 if (iAction.Value == "r\uFFFD")
                 {
                     ActiveUp.Net.Mail.Mailbox        mailbox1       = ((ActiveUp.Net.Mail.Imap4Client)Session["imapobject\uFFFD"]).SelectMailbox(MailboxName);
                     ActiveUp.Net.Mail.FlagCollection flagCollection = new ActiveUp.Net.Mail.FlagCollection();
                     flagCollection.Add("Answered\uFFFD");
                     if (mailbox1.Fetch.Flags(MessageId).Merged.ToLower().IndexOf("\\answered\uFFFD") == -1)
                     {
                         mailbox1.AddFlagsSilent(MessageId, flagCollection);
                     }
                 }
                 lConfirm.Text    = ((Language)Session["language\uFFFD"]).Words[32].ToString() + " : <br /><br />\uFFFD" + message.To.Merged + message.Cc.Merged + message.Bcc.Merged.Replace(";\uFFFD", "<br />\uFFFD");
                 pForm.Visible    = false;
                 pConfirm.Visible = true;
                 System.Web.HttpCookie httpCookie1 = new System.Web.HttpCookie("fromname\uFFFD", iFromName.Text);
                 System.Web.HttpCookie httpCookie2 = new System.Web.HttpCookie("fromemail\uFFFD", iFromEmail.Text);
                 System.Web.HttpCookie httpCookie3 = new System.Web.HttpCookie("replyto\uFFFD", iReplyTo.Text);
                 System.DateTime       dateTime1   = System.DateTime.Now;
                 httpCookie1.Expires = dateTime1.AddMonths(2);
                 System.DateTime dateTime2 = System.DateTime.Now;
                 httpCookie2.Expires = dateTime2.AddMonths(2);
                 System.DateTime dateTime3 = System.DateTime.Now;
                 httpCookie3.Expires = dateTime3.AddMonths(2);
                 Response.Cookies.Add(httpCookie1);
                 Response.Cookies.Add(httpCookie2);
                 Response.Cookies.Add(httpCookie3);
                 if (cSave.Checked)
                 {
                     System.Web.HttpCookie httpCookie4 = new System.Web.HttpCookie("folder\uFFFD", dBoxes.SelectedItem.Text);
                     System.DateTime       dateTime4   = System.DateTime.Now;
                     httpCookie4.Expires = dateTime4.AddMonths(2);
                     Response.Cookies.Add(httpCookie4);
                     ActiveUp.Net.Mail.Mailbox mailbox2 = ((ActiveUp.Net.Mail.Imap4Client)Session["imapobject\uFFFD"]).SelectMailbox(dBoxes.SelectedItem.Text);
                     mailbox2.Append(message.ToMimeString());
                 }
                 string[] sArr6 = System.IO.Directory.GetFiles(Page.Server.MapPath(Application["writedirectory\uFFFD"].ToString()));
                 for (int i4 = 0; i4 < sArr6.Length; i4++)
                 {
                     string s5 = sArr6[i4];
                     if (s5.IndexOf(Session.SessionID) != -1)
                     {
                         System.IO.File.Delete(s5);
                     }
                 }
             }
             catch (System.Exception e1)
             {
                 Page.RegisterStartupScript("ShowError\uFFFD", "<script>ShowErrorDialog('\uFFFD" + ((Language)Session["language\uFFFD"]).Words[83].ToString() + "','\uFFFD" + System.Text.RegularExpressions.Regex.Escape(e1.Message + e1.StackTrace).Replace("'\uFFFD", "\\'\uFFFD") + "');</script>\uFFFD");
             }
         }
         else
         {
             System.Web.HttpCookie httpCookie5 = new System.Web.HttpCookie("folder\uFFFD", dBoxes.SelectedItem.Text);
             System.DateTime       dateTime5   = System.DateTime.Now;
             httpCookie5.Expires = dateTime5.AddMonths(2);
             Response.Cookies.Add(httpCookie5);
             ActiveUp.Net.Mail.Mailbox mailbox3 = ((ActiveUp.Net.Mail.Imap4Client)Session["imapobject\uFFFD"]).SelectMailbox(dBoxes.SelectedItem.Text);
             mailbox3.Append(message.ToMimeString());
         }
         string[] sArr8 = System.IO.Directory.GetFiles(Page.Server.MapPath(Application["writedirectory\uFFFD"].ToString()));
         for (int i5 = 0; i5 < sArr8.Length; i5++)
         {
             string s6 = sArr8[i5];
             if (s6.IndexOf(Session.SessionID) != -1)
             {
                 System.IO.File.Delete(s6);
             }
         }
     }
     catch (System.Exception e2)
     {
         Page.RegisterStartupScript("ShowError\uFFFD", "<script>ShowErrorDialog('\uFFFD" + ((Language)Session["language\uFFFD"]).Words[82].ToString() + "','\uFFFD" + System.Text.RegularExpressions.Regex.Escape(e2.Message + e2.StackTrace).Replace("'\uFFFD", "\\'\uFFFD") + "');</script>\uFFFD");
     }
 }
 /// <summary>
 /// Add a MimePart to the embedded objects collection.
 /// </summary>
 /// <param name="part"></param>
 public new void Add(MimePart part)
 {
     part.ContentDisposition.Disposition = "inline";
     List.Add(part);
 }
Exemple #28
0
        /// <summary>
        /// Parses the message.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public static Message ParseMessage(byte[] data)
        {
            //string msg = System.Text.Encoding.ASCII.GetString(data);
#if !PocketPC
            string msg = System.Text.Encoding.UTF8.GetString(data, 0, data.Length);
#else
            string msg = Pop3Client.PPCEncode.GetString(data, 0, data.Length);
#endif

            Message message = new Message();

            try
            {
                // Build a part tree and get all headers.
                MimePart part = ParseMimePart(msg, message);

                // Fill a new message object with the new information.
                message.OriginalData     = data;
                message.HeaderFields     = part.HeaderFields;
                message.HeaderFieldNames = part.HeaderFieldNames;

                // Dispatch header fields to corresponding object.
                foreach (string key in message.HeaderFields.AllKeys)
                {
                    string name  = key;
                    string value = message.HeaderFields[key];
                    // TODO : Fix trace
                    if (name.Equals("received"))
                    {
                        message.Trace.Add(Parser.ParseTrace(key + ": " + value));
                    }
                    else if (name.Equals("to"))
                    {
                        message.To = Parser.ParseAddresses(value);
                    }
                    else if (name.Equals("cc"))
                    {
                        message.Cc = Parser.ParseAddresses(value);
                    }
                    else if (name.Equals("bcc"))
                    {
                        message.Bcc = Parser.ParseAddresses(value);
                    }
                    else if (name.Equals("reply-to"))
                    {
                        message.ReplyTo = Parser.ParseAddress(value);
                    }
                    else if (name.Equals("from"))
                    {
                        message.From = Parser.ParseAddress(value);
                    }
                    else if (name.Equals("sender"))
                    {
                        message.Sender = Parser.ParseAddress(value);
                    }
                    else if (name.Equals("content-type"))
                    {
                        message.ContentType = Parser.GetContentType(key + ": " + value);
                    }
                    else if (name.Equals("content-disposition"))
                    {
                        message.ContentDisposition = Parser.GetContentDisposition(key + ": " + value);
                    }
                    else if (name.Equals("domainkey-signature"))
                    {
                        message.Signatures.DomainKeys = Signature.Parse(key + ": " + value, message);
                    }
                }

                if (message.ContentType.MimeType.Equals("application/pkcs7-mime") ||
                    message.ContentType.MimeType.Equals("application/x-pkcs7-mime"))
                {
                    if (message.ContentType.Parameters["smime-type"] != null &&
                        message.ContentType.Parameters["smime-type"].Equals("enveloped-data"))
                    {
                        message.IsSmimeEncrypted = true;
                    }
                    if (message.ContentType.Parameters["smime-type"] != null &&
                        message.ContentType.Parameters["smime-type"].Equals("signed-data"))
                    {
                        message.HasSmimeSignature = true;
                    }
                }

                if (message.ContentType.MimeType.Equals("multipart/signed"))
                {
                    message.HasSmimeDetachedSignature = true;
                }

                // Keep a reference to the part tree within the new Message object.
                message.PartTreeRoot = part;

                DispatchParts(ref message);

                // Dispatch the part tree content to the appropriate collections and properties.
                // TODO
            }
            catch (Exception ex)
            {
                if (ErrorParsing != null)
                {
                    ErrorParsing(null, ex);
                }
            }
            return(message);
        }
Exemple #29
0
		/*public static MimePart ParsePart(string data, X509Certificate2Collection certificates, SignedCms signature)
		{
            MimePart part = new MimePart();
            if (signature.Certificates.Count != 0) part.IsSigned = true;
            part.Signature = signature;
            
            string header = data.Substring(0,Regex.Match(data, @"\r?\n\r?\n").Index);
            Match m = Regex.Match(header, @"(?<=((\r?\n)|\n)|\A)\S+:(.|(\r?\n[\t ]))+(?=((\r?\n)\S)|\Z)");
            while (m.Success)
            {
                if (m.Value.ToLower().StartsWith("content-type:")) part.ContentType = Parser.GetContentType(m.Value);
                else if (m.Value.ToLower().StartsWith("content-disposition:")) part.ContentDisposition = Parser.GetContentDisposition(m.Value);
                part.HeaderFields.Add(FormatFieldName(m.Value.Substring(0, m.Value.IndexOf(':'))), m.Value.Substring(m.Value.IndexOf(':') + 1));
                m = m.NextMatch();
            }
            
            // S/MIME support
            // TODO : Differenciate by ASN.1 decoding
            if (part.ContentType.MimeType!=null && (part.ContentType.MimeType.IndexOf("application/x-pkcs7-mime") != -1 || part.ContentType.MimeType.IndexOf("application/pkcs7-mime") != -1))
            {
                if (part.ContentType.Parameters["smime-type"]!=null && part.ContentType.Parameters["smime-type"].ToLower().IndexOf("signed-data") != -1)
                {
                    part.IsSigned = true;
                    string contentBase64 = data.Substring(Regex.Match(data, @"\r?\n\r?\n").Index);
                    byte[] signedData = System.Convert.FromBase64String(contentBase64);
                    SignedCms sig = new SignedCms();
                    sig.Decode(signedData);
                    
                    return ParsePart(System.Text.Encoding.ASCII.GetString(sig.ContentInfo.Content), certificates, sig);
                }
                else
                {
                    part.IsEncrypted = true;
                    string contentBase64 = data.Substring(Regex.Match(data, @"\r?\n\r?\n").Index);
                    EnvelopedCms env = new EnvelopedCms();
                    env.Decode(System.Convert.FromBase64String(contentBase64));
                    env.Decrypt(certificates);
                    byte[] decryptedContent = env.ContentInfo.Content;
                    
                    return ParsePart(System.Text.Encoding.ASCII.GetString(decryptedContent), certificates);
                }
            }
            if (part.Charset==null || part.Charset.Length < 1) part.Charset = "us-ascii";
            byte[] binData = System.Text.Encoding.ASCII.GetBytes(data);
            try { part.TextContent = System.Text.Encoding.GetEncoding(part.Charset).GetString(binData); }
		    catch { part.TextContent = data; }
            m = Regex.Match(part.TextContent,@"\r?\n\r?\n");
			part.TextContent = part.TextContent.Substring(m.Index+m.Length);
            
            if (part.ContentType.MimeType != null && part.ContentType.MimeType.IndexOf("multipart/signed") != -1) part.IsSigned = true;
            if (part.ContentTransferEncoding==ContentTransferEncoding.QuotedPrintable) part.TextContent = Codec.FromQuotedPrintable(part.TextContent,part.Charset);
            if (part.ContentTransferEncoding == ContentTransferEncoding.Base64)
            {
                part.TextContent = part.TextContent.Trim('\r', '\n');
                part.BinaryContent = System.Convert.FromBase64String(part.TextContent);
            }
            else part.BinaryContent = System.Text.Encoding.GetEncoding(part.Charset).GetBytes(part.TextContent);
			
            return part;
		}*/

        private static MultipartContainer ParseMultipartContainer(MimePart part)
        {
            MultipartContainer container = new MultipartContainer();
            string boundary = part.ContentType.Parameters["boundary"];
            string[] arrpart = Regex.Split(part.TextContent, @"\r?\n?" + Regex.Escape("--" + boundary));
            for (int i = 0; i < arrpart.Length; i++)
            {
                string strpart = arrpart[i];
                if (!strpart.StartsWith("--"))
                {
                    container.PartTree.Add(Parser.ParseMimeTypedAndEncodedContent(strpart));
                }
            }
            return container;
        }
Exemple #30
0
 /// <summary>
 /// Parses the sub parts.
 /// </summary>
 /// <param name="part">The part.</param>
 private static void ParseSubParts(ref MimePart part, Message message)
 {
     string boundary = part.ContentType.Parameters["boundary"];
     ActiveUp.Net.Mail.Logger.AddEntry("boundary : " + boundary);
     string[] arrpart = Regex.Split(part.OriginalContent, @"\r?\n?" + Regex.Escape("--" + boundary));
     for (int i = 1; i < arrpart.Length - 1; i++)
     {
         string strpart = arrpart[i];
         if (!strpart.StartsWith("--") && !string.IsNullOrEmpty(strpart))
         {
             MimePart newpart = Parser.ParseMimePart(strpart, message);
             newpart.ParentMessage = message;
             newpart.Container = part;
             part.SubParts.Add(newpart);
         }
     }
 }
Exemple #31
0
        /// <summary>
        /// Generates the confirm read message.
        /// </summary>
        /// <returns></returns>
        public Message GenerateConfirmReadMessage()
        {
            Message message = new Message();

            // Inverse the recipient and sender
            message.To.Add(this.ConfirmRead);
            message.From = this.To[0];

            // Create the subject
            message.Subject = "Read: " + this.Subject;

            // Adds the original message ID
            
            message.AddHeaderField("In-Reply-To", this.MessageId);

            // Prepare the bodies

            DateTime dateReceived = this.Date;
            DateTime dateRead = DateTime.Now;

            message.BodyText.Text = string.Format(@"Your message

    To:  {0}
    Subject:  {1}
    Sent:  {2} {3}

was read on {4} {5}.", this.To[0].Email, this.Subject, dateReceived.ToShortDateString(), dateReceived.ToShortTimeString(),
                 dateRead.ToShortDateString(), dateRead.ToShortTimeString());

            message.BodyHtml.Text = string.Format(@"<P><FONT SIZE=3D2>Your message<BR>
<BR>
&nbsp;&nbsp;&nbsp; To:&nbsp; {0}<BR>
&nbsp;&nbsp;&nbsp; Subject:&nbsp; {1}<BR>
&nbsp;&nbsp;&nbsp; Sent:&nbsp; {2} {3}<BR>
<BR>
was read on {4} {5}.</FONT>
</P>", this.To[0].Email, this.Subject, dateReceived.ToShortDateString(), dateReceived.ToShortTimeString(),
                 dateRead.ToShortDateString(), dateRead.ToShortTimeString());

            // Create the repot mime part
            MimePart notificationPart = new MimePart();
            notificationPart.ContentType.MimeType = "message/disposition-notification";
            notificationPart.ContentTransferEncoding = ContentTransferEncoding.QuotedPrintable;

            notificationPart.TextContent = string.Format(@"Reporting-UA: {0}; ActiveUp.MailSystem
Final-Recipient: rfc822;{1}
Original-Message-ID: <{2}>
Disposition: manual-action/MDN-sent-manually; displayed", "domain", this.To[0].Email, this.MessageId);

            message.UnknownDispositionMimeParts.Add(notificationPart);

            // Now we return the result
            return message;
        }
Exemple #32
0
        private static void DispatchPart(MimePart part, ref Message message)
        {
            // This is a container part.
            if (part.SubParts.Count > 0) DispatchParts(part, ref message);
            // This is a leaf part.
            else
            {
                // If this part has to be displayed has an attachment, add it to the appropriate collection.
                if (part.ContentDisposition.Disposition.Equals("attachment")) message.Attachments.Add(part);
                // If this part has to be displayed at the same time as the main body, add it to the appropriate collection.
                else if (part.ContentDisposition.Disposition.Equals("inline")) message.EmbeddedObjects.Add(part);
                // Other parts are miscellaneous. How they are to be displayed is at the end-user's discretion.
                // Fix for avoid attach original mail message
                else if(!message.BodyText.ToMimePart().ContentTransferEncoding.Equals(part.ContentTransferEncoding))
                {
                    message.UnknownDispositionMimeParts.Add(part);
                }

                // We will consider the highest-level text parts that are not attachments to be the intended for display.
                // We know the highest-level parts will be set, because the parser first goes to the deepest level and returns top-level parts last.
                if (part.ContentType.Type.Equals("text") && !part.ContentDisposition.Disposition.Equals("attachment"))
                {
                    if (part.ContentType.SubType.Equals("plain"))
                    {
                        message.BodyText.Charset = part.Charset;
                        message.BodyText.Text = part.TextContent;
                    }
                    else if (part.ContentType.SubType.Equals("html"))
                    {
                        message.IsHtml = true;
                        message.BodyHtml.Charset = part.Charset;
                        message.BodyHtml.Text = part.TextContent;
                    }
                }

                // Parse message/rfc822 parts as Message objects and place them in the appropriate collection.
                if (part.ContentType.MimeType.Equals("message/rfc822"))
                    message.SubMessages.Add(Parser.ParseMessage(part.BinaryContent));

                if (part.ContentType.MimeType.Equals("application/pkcs7-signature")
                    || part.ContentType.MimeType.Equals("application/x-pkcs7-signature"))
                {
                    string toDigest = part.Container.TextContent;
                    toDigest = Regex.Split(toDigest, "\r\n--" + part.Container.ContentType.Parameters["boundary"])[1];
                    toDigest = toDigest.TrimStart('\r', '\n');
                    //Match endDelimiter = Regex.Match(toDigest, "(?<=[^\r\n]\r\n)\r\n", RegexOptions.RightToLeft);
                    //int lastNonNewLine = Regex.Match(toDigest, "[^\r\n]", RegexOptions.RightToLeft).Index;
                    //if (endDelimiter.Index != -1 && endDelimiter.Index > lastNonNewLine) toDigest = toDigest.Remove(endDelimiter.Index);

                    //TODO: What should be done in PPC ?
#if !PocketPC
                    message.Signatures.Smime = new SignedCms(new ContentInfo(Encoding.ASCII.GetBytes(toDigest)), true);
                    message.Signatures.Smime.Decode(part.BinaryContent);
#endif
                }

                // Anyway, this is a leaf part of the message.
                message.LeafMimeParts.Add(part);
            }
        }
Exemple #33
0
        private MimePart GetBodiesPart()
        {
            MimePart bodies = new MimePart();

            bool html = (this.BodyHtml.Text.Length > 0);
            bool plain = (this.BodyText.Text.Length > 0);

            // If we have both, make a multipart/alternative container.
            if (html && plain)
            {
                bodies.ContentType.MimeType = "multipart/alternative";

                string unique = Codec.GetUniqueString();
                string boundary = "---AU_MimePart_" + unique;
                bodies.ContentType.Parameters.Add("boundary", boundary);

                bodies.SubParts.Add(this.BodyText.ToMimePart());
                bodies.SubParts.Add(this.BodyHtml.ToMimePart());
            }
            else if (html)
            {
                bodies = this.BodyHtml.ToMimePart();
            }
            else if (plain)
            {
                bodies = this.BodyText.ToMimePart();
            }

            return bodies;
        }
Exemple #34
0
        /// <summary>
        /// Parses the MIME part.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public static MimePart ParseMimePart(string data, Message message)
        {
            MimePart part = new MimePart();
            part.ParentMessage = message;
            part.OriginalContent = data;

            try
            {
                // Separate header and body.
                int headerEnd = Regex.Match(data, @".(?=\r?\n\r?\n)").Index + 1;
                int bodyStart = Regex.Match(data, @"(?<=\r?\n\r?\n).").Index;

                //TODO: remove this workaround
                if (bodyStart == 0)
                {
                    //bodyStart = data.IndexOf("\r\n\r\n");
                    // Fix for a bug - the bodyStart was -1 (Invalid), MCALADO: 04/07/2008
                    int indexBody = data.IndexOf("\r\n\r\n");
                    if (indexBody > 0)
                    {
                        bodyStart = indexBody;
                    }
                }
                if (data.Length >= headerEnd)
                {

                    string header = data.Substring(0, headerEnd);

                    header = Parser.Unfold(header);
                    //header = header);

                    // The bodyStart need to be greather than data.length - MCALADO: 04/07/2008
                    string body = string.Empty;
                    if (bodyStart < data.Length)
                    {
                        body = data.Substring(bodyStart);
                    }

                    // Store the (maybe still encoded) body.
                    part.TextContent = body;




                    // Parse header fields and their parameters.
                    Match m = Regex.Match(header, @"(?<=((\r?\n)|\n)|\A)\S+:(.|(\r?\n[\t ]))+(?=((\r?\n)\S)|\Z)");
                    while (m.Success)
                    {
                        if (m.Value.ToLower().StartsWith("content-type:"))
                        {
                            part.ContentType = Parser.GetContentType(m.Value);
                        }
                        else if (m.Value.ToLower().StartsWith("content-disposition:"))
                        {
                            part.ContentDisposition = Parser.GetContentDisposition(m.Value);
                        }
                        part.HeaderFields.Add(FormatFieldName(m.Value.Substring(0, m.Value.IndexOf(':'))), Codec.RFC2047Decode(m.Value.Substring(m.Value.IndexOf(':') + 1).Trim(' ', '\r', '\n')));
                        part.HeaderFieldNames.Add(FormatFieldName(m.Value.Substring(0, m.Value.IndexOf(':'))), Codec.RFC2047Decode(m.Value.Substring(0, m.Value.IndexOf(':')).Trim(' ', '\r', '\n')));
                        m = m.NextMatch();
                    }

                    // Build the part tree.

                    // This is a container part.
                    if (part.ContentType.Type.ToLower().Equals("multipart"))
                    {
                        Parser.ParseSubParts(ref part, message);
                    }
                    // This is a nested message.
                    else if (part.ContentType.Type.ToLower().Equals("message"))
                    {
                        // TODO
                    }
                    // This is a leaf of the part tree
                    // Check necessary for single part emails (fix from alex294 on CodePlex)
                    // Why would we consider the body only to the first string?  Doesn't make sense - and fails
                    //else if (part.ContentType.Type.ToLower().Equals("text"))
                    //{
                    //    int BodyEnd = body.IndexOf(' ');
                    //    if (BodyEnd > 0)
                    //    {
                    //        part.TextContent = body.Substring(0, BodyEnd);
                    //    }
                    //}

                    DecodePartBody(ref part);

                    try
                    {
                        BodyParsed(null, message);
                    }
                    catch (Exception)
                    {
                        // event is not supported.
                    }
                }

            }
            catch (Exception ex)
            {
                throw new ParsingException(ex.Message);
            }

            return part;
        }
Exemple #35
0
        private MimePart GetMultipartMixedContainer()
        {
            MimePart part = new MimePart();

            if (this.Attachments.Count > 0
                || this.UnknownDispositionMimeParts.Count > 0
                || this.SubMessages.Count > 0)
            {
                part.ContentType.MimeType = "multipart/mixed";

                string unique = Codec.GetUniqueString();
                string boundary = "---AU_MimePart_" + unique;
                part.ContentType.Parameters.Add("boundary", boundary);

                part.SubParts.Add(this.GetMultipartRelatedContainer());

                foreach (MimePart attachment in this.Attachments)
                    part.SubParts.Add(attachment);

                foreach (MimePart otherpart in this.UnknownDispositionMimeParts)
                    part.SubParts.Add(otherpart);

                foreach (Message message in this.SubMessages)
                    part.SubParts.Add(message.ToMimePart());
            }
            else part = this.GetMultipartRelatedContainer();

            return part;
        }
Exemple #36
0
        public void AddAttachmentFromString(string filename, string body)
        {
            var decoded_bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(body);

            var text_attach = new MimePart(decoded_bytes, filename);

            Attachments.Add(text_attach);
        }
Exemple #37
0
        private static void DispatchPart(MimePart part, ref Message message)
        {
            // This is a container part.
            if (part.SubParts.Count > 0)
            {
                DispatchParts(part, ref message);
            }
            // This is a leaf part.
            else
            {
                // If this part has to be displayed has an attachment, add it to the appropriate collection.
                if (part.ContentDisposition.Disposition.Equals("attachment"))
                {
                    message.Attachments.Add(part);
                }
                // If this part has to be displayed at the same time as the main body, add it to the appropriate collection.
                else if (part.ContentDisposition.Disposition.Equals("inline"))
                {
                    message.EmbeddedObjects.Add(part);
                }
                // Other parts are miscellaneous. How they are to be displayed is at the end-user's discretion.
                // Fix for avoid attach original mail message
                else if (!message.BodyText.ToMimePart().ContentTransferEncoding.Equals(part.ContentTransferEncoding))
                {
                    message.UnknownDispositionMimeParts.Add(part);
                }

                // We will consider the highest-level text parts that are not attachments to be the intended for display.
                // We know the highest-level parts will be set, because the parser first goes to the deepest level and returns top-level parts last.
                if (part.ContentType.Type.Equals("text") && !part.ContentDisposition.Disposition.Equals("attachment"))
                {
                    if (part.ContentType.SubType.Equals("plain"))
                    {
                        message.BodyText.Charset = part.Charset;
                        message.BodyText.Text    = part.TextContent;
                    }
                    else if (part.ContentType.SubType.Equals("html"))
                    {
                        message.IsHtml           = true;
                        message.BodyHtml.Charset = part.Charset;
                        message.BodyHtml.Text    = part.TextContent;
                    }
                    else if (part.ContentType.SubType.Equals("xml"))
                    {
                        //Recupera anexos que nao estejam marcados com 'Content-Disposition' e 'attachment'. Alguns anexos com mimetype xml podem ter essa caracteristica.
                        //Recovers attachments that are not marked with 'Content-Disposition' 'attachment'. Some attachments with xml mime-type may have this feature.
                        message.Attachments.Add(part);
                    }
                }

                // Parse message/rfc822 parts as Message objects and place them in the appropriate collection.
                if (part.ContentType.MimeType.Equals("message/rfc822"))
                {
                    message.SubMessages.Add(Parser.ParseMessage(part.BinaryContent));
                }

                if (part.ContentType.MimeType.Equals("application/pkcs7-signature") ||
                    part.ContentType.MimeType.Equals("application/x-pkcs7-signature"))
                {
                    string toDigest = part.Container.TextContent;
                    toDigest = Regex.Split(toDigest, "\r\n--" + part.Container.ContentType.Parameters["boundary"])[1];
                    toDigest = toDigest.TrimStart('\r', '\n');
                    //Match endDelimiter = Regex.Match(toDigest, "(?<=[^\r\n]\r\n)\r\n", RegexOptions.RightToLeft);
                    //int lastNonNewLine = Regex.Match(toDigest, "[^\r\n]", RegexOptions.RightToLeft).Index;
                    //if (endDelimiter.Index != -1 && endDelimiter.Index > lastNonNewLine) toDigest = toDigest.Remove(endDelimiter.Index);

                    //TODO: What should be done in PPC ?
#if !PocketPC
                    message.Signatures.Smime = new SignedCms(new ContentInfo(Encoding.ASCII.GetBytes(toDigest)), true);
                    message.Signatures.Smime.Decode(part.BinaryContent);
#endif
                }

                // Anyway, this is a leaf part of the message.
                message.LeafMimeParts.Add(part);
            }
        }
Exemple #38
0
        /// <summary>
        /// Encrypts the message and envelopes it for multiple recipients.
        /// </summary>
        /// <param name="recipients">An object containing the recipients' certificates with public keys.</param>
        /// <example>
        /// <code>
        /// [C#]
        /// 
        /// CmsRecipientCollection recipients = new CmsRecipientCollection();
        /// 
        /// recipients.Add(new CmsRecipient(new X509Certificate2("C:\\recipient1.cer")));
        /// recipients.Add(new CmsRecipient(new X509Certificate2("C:\\recipient2.cer")));
        /// 
        /// message.SmimeEnvelopeAndEncryptFor(recipients);
        /// </code>
        /// </example>
        public void SmimeEnvelopeAndEncryptFor(CmsRecipientCollection recipients)
        {
            string mimeString = this.ToMimeString();
            byte[] toencrypt = Encoding.ASCII.GetBytes(mimeString);
            EnvelopedCms cms = new EnvelopedCms(new ContentInfo(toencrypt));
            cms.Encrypt(recipients);

            MimePart envelope = new MimePart();

            envelope.ContentType.MimeType = "application/pkcs7-mime";
            envelope.ContentType.Parameters.Add("smime-type", "encrypted-data");
            envelope.ContentType.Parameters.Add("name", "smime.p7m");
            envelope.ContentDisposition.Disposition = "attachment";
            envelope.ContentDisposition.FileName = "smime.p7m";
            envelope.ContentTransferEncoding = ContentTransferEncoding.Base64;

            envelope.BinaryContent = cms.Encode();

            this.PartTreeRoot = envelope;

            this.ContentType = this.PartTreeRoot.ContentType;
            this.ContentDisposition = this.PartTreeRoot.ContentDisposition;
            this.ContentTransferEncoding = this.PartTreeRoot.ContentTransferEncoding;
        }
Exemple #39
0
        /// <summary>
        /// Decodes the part body.
        /// </summary>
        /// <param name="part">The part.</param>
        private static void DecodePartBody(ref MimePart part)
        {
            // Let's see if a charset is specified. Otherwise we default to "iso-8859-1".
            string charset = (!string.IsNullOrEmpty(part.Charset) ? part.Charset : "iso-8859-1");

#if PocketPC
            if (charset.ToLower() == "iso-8859-1")
            {
                charset = "windows-1252";
            }
#endif
            // This is a Base64 encoded part body.
            if (part.ContentTransferEncoding.Equals(ContentTransferEncoding.Base64))
            {
#if !PocketPC
                try
                {
#endif
                //We have the Base64 string so we can decode it.
                part.BinaryContent = Convert.FromBase64String(part.TextContent);
#if !PocketPC
            }
            catch (System.FormatException)
            {
                part.TextContent   = part.TextContent.Remove(part.TextContent.LastIndexOf("="));
                part.BinaryContent = Convert.FromBase64String(part.TextContent);
            }
#endif

                if (part.ContentDisposition != ContentDisposition.Attachment)
                {
                    // Attenzione!!
                    // sostituito da Luigi per encoding di windows
                    //part.TextContent = System.Text.Encoding.GetEncoding(charset).GetString(part.BinaryContent,0,part.BinaryContent.Length);
                    part.TextContent = Codec.GetEncoding(charset).GetString(part.BinaryContent, 0, part.BinaryContent.Length);
                }
            }
            // This is a quoted-printable encoded part body.
            else if (part.ContentTransferEncoding.Equals(ContentTransferEncoding.QuotedPrintable))
            {
                //else if (part.Container != null && part.Container.Charset != null && part.Container.Charset.Length > 0)
                //    charset = part.Container.Charset;

                // Let's decode.
                part.TextContent = Codec.FromQuotedPrintable(part.TextContent, charset);
                // Knowing the charset, we can provide a binary version of this body data.
                // Attenzione!!
                // sostituito da Luigi per encoding di windows
                //part.BinaryContent = Encoding.GetEncoding(charset).GetBytes(part.TextContent);
                part.BinaryContent = Codec.GetEncoding(charset).GetBytes(part.TextContent);
            }
            // Otherwise, this is an unencoded part body and we keep the text version as it is.
            else
            {
                // Knowing the charset, we can provide a binary version of this body data.
                // Attenzione!!
                // sostituito da Luigi per encoding di windows
                //part.BinaryContent = Encoding.GetEncoding(charset).GetBytes(part.TextContent);
                part.BinaryContent = Codec.GetEncoding(charset).GetBytes(part.TextContent);
            }
        }
Exemple #40
0
        /// <summary>
        /// Attaches a clear signature to the message. It is advised to do so when the receiving party might not be S/MIME capable.
        /// The content of the message is still visible, i.e. the message isn't enveloped.
        /// </summary>
        /// <param name="signer">An object containing the signer's information.</param>
        /// <example>
        /// <code>
        /// [C#]
        /// 
        /// CmsSigner signer = new CmsSigner(new X509Certificate2("C:\\mycertificate.pfx"));
        /// 
        /// // Here we only want the signer's certificate to be sent along. Not the whole chain.
        /// signer.IncludeOption = X509IncludeOption.EndCertOnly;
        /// 
        /// message.SmimeAttachSignatureBy(signer);
        /// </code>
        /// </example>
        public void SmimeAttachSignatureBy(CmsSigner signer)
        {
            string body = this.PartTreeRoot.ToMimeString();
            byte[] tosign = Encoding.ASCII.GetBytes(body.TrimEnd('\r', '\n') + "\r\n");

            SignedCms cms = new SignedCms(new ContentInfo(tosign), true);
            cms.ComputeSignature(signer);

            MimePart envelope = new MimePart();

            this.Signatures.Smime = cms;
            envelope.ContentType.MimeType = "multipart/signed";
            envelope.ContentType.Parameters.Add("protocol", "\"application/x-pkcs7-signature\"");
            envelope.ContentType.Parameters.Add("micalg", cms.SignerInfos[0].DigestAlgorithm.FriendlyName);
            string unique = Codec.GetUniqueString();
            string boundary = "---AU_MimePart_" + unique;
            envelope.ContentType.Parameters.Add("boundary", boundary);

            envelope.SubParts.Add(this.PartTreeRoot);
            envelope.SubParts.Add(MimePart.GetSignaturePart(cms));

            this.PartTreeRoot = envelope;

            this.ContentType = this.PartTreeRoot.ContentType;
            this.ContentDisposition = this.PartTreeRoot.ContentDisposition;
            this.ContentTransferEncoding = this.PartTreeRoot.ContentTransferEncoding;
        }
 public void Send(object sender, System.EventArgs e)
 {
     ActiveUp.Net.Mail.Message message = new ActiveUp.Net.Mail.Message();
     try
     {
         message.Subject = iSubject.Text;
         message.To = ActiveUp.Net.Mail.Parser.ParseAddresses(iTo.Text);
         message.Cc = ActiveUp.Net.Mail.Parser.ParseAddresses(iCc.Text);
         message.Bcc = ActiveUp.Net.Mail.Parser.ParseAddresses(iBcc.Text);
         if (iReplyTo.Text.Length > 0)
             message.ReplyTo = ActiveUp.Net.Mail.Parser.ParseAddresses(iReplyTo.Text)[0];
         string s1 = iBody.Text;
         string[] sArr1 = System.IO.Directory.GetFiles(Page.Server.MapPath(Application["writedirectory\uFFFD"].ToString()));
         for (int i1 = 0; i1 < sArr1.Length; i1++)
         {
             string s2 = sArr1[i1];
             if ((s2.IndexOf(Session.SessionID + "_Image_\uFFFD") != -1) && (s1.IndexOf(s2.Substring(s2.IndexOf(Session.SessionID))) != -1))
             {
                 ActiveUp.Net.Mail.MimePart embeddedObject1 = new ActiveUp.Net.Mail.MimePart(s2, true, string.Empty);
                 embeddedObject1.ContentName = s2.Substring(s2.IndexOf("_Image_\uFFFD") + 7);
                 message.EmbeddedObjects.Add(embeddedObject1);
                 s1 = s1.Replace("http://\uFFFD" + Request.ServerVariables["HTTP_HOST\uFFFD"] + Request.ServerVariables["URL\uFFFD"].Substring(0, Request.ServerVariables["URL\uFFFD"].LastIndexOf("/\uFFFD") + 1) + "temp\uFFFD" + s2.Substring(s2.LastIndexOf('\\')).Replace("\\\uFFFD", "/\uFFFD"), "cid:\uFFFD" + embeddedObject1.ContentId);
                 s1 = s1.Replace("temp\uFFFD" + s2.Substring(s2.LastIndexOf('\\')).Replace("\\\uFFFD", "/\uFFFD"), "cid:\uFFFD" + embeddedObject1.ContentId);
             }
         }
         string[] sArr3 = System.IO.Directory.GetFiles(Server.MapPath("icons/emoticons/\uFFFD"));
         for (int i2 = 0; i2 < sArr3.Length; i2++)
         {
             string s3 = sArr3[i2];
             if (s1.IndexOf("icons/emoticons\uFFFD" + s3.Substring(s3.LastIndexOf("\\\uFFFD")).Replace("\\\uFFFD", "/\uFFFD")) != -1)
             {
                 ActiveUp.Net.Mail.MimePart embeddedObject2 = new ActiveUp.Net.Mail.MimePart(s3, true, string.Empty);
                 embeddedObject2.ContentName = s3.Substring(s3.LastIndexOf("\\\uFFFD") + 1);
                 message.EmbeddedObjects.Add(embeddedObject2);
                 s1 = s1.Replace("http://\uFFFD" + Request.ServerVariables["HTTP_HOST\uFFFD"] + Request.ServerVariables["URL\uFFFD"].Substring(0, Request.ServerVariables["URL\uFFFD"].LastIndexOf("/\uFFFD") + 1) + "icons/emoticons\uFFFD" + s3.Substring(s3.LastIndexOf('\\')).Replace("\\\uFFFD", "/\uFFFD"), "cid:\uFFFD" + embeddedObject2.ContentId);
             }
         }
         message.BodyHtml.Text = s1;
         message.BodyText.Text = iBody.TextStripped;
         //message.Headers.Add("x-sender-ip\uFFFD", Request.ServerVariables["REMOTE_ADDR\uFFFD"]);
         string[] sArr5 = System.IO.Directory.GetFiles(Page.Server.MapPath(Application["writedirectory\uFFFD"].ToString()));
         for (int i3 = 0; i3 < sArr5.Length; i3++)
         {
             string s4 = sArr5[i3];
             if (s4.IndexOf("\\temp\\\uFFFD" + Session.SessionID + "_Attach_\uFFFD") != -1)
             {
                 ActiveUp.Net.Mail.MimePart attachment = new ActiveUp.Net.Mail.MimePart(s4, true);
                 attachment.Filename = s4.Substring(s4.IndexOf("_Attach_\uFFFD") + 8);
                 attachment.ContentName = s4.Substring(s4.IndexOf("_Attach_\uFFFD") + 8);
                 message.Attachments.Add(attachment);
             }
         }
         message.From = new ActiveUp.Net.Mail.Address(iFromEmail.Text, iFromName.Text);
         if (((System.Web.UI.HtmlControls.HtmlInputButton)sender).ID == "iSubmit\uFFFD")
         {
             try
             {
                 message.Send((string)Application["smtpserver\uFFFD"], System.Convert.ToInt32(Application["smtpport\uFFFD"]), (string)Application["user\uFFFD"], (string)Application["password\uFFFD"], ActiveUp.Net.Mail.SaslMechanism.CramMd5);
             }
             catch
             {
                 try
                 {
                     message.Send((string)Application["smtpserver\uFFFD"], System.Convert.ToInt32(Application["smtpport\uFFFD"]), (string)Application["user\uFFFD"], (string)Application["password\uFFFD"], ActiveUp.Net.Mail.SaslMechanism.CramMd5);
                 }
                 catch
                 {
                     message.Send((string)Application["smtpserver\uFFFD"], System.Convert.ToInt32(Application["smtpport\uFFFD"]));
                 }
             }
             try
             {
                 if (iAction.Value == "r\uFFFD")
                 {
                     ActiveUp.Net.Mail.Mailbox mailbox1 = ((ActiveUp.Net.Mail.Imap4Client)Session["imapobject\uFFFD"]).SelectMailbox(MailboxName);
                     ActiveUp.Net.Mail.FlagCollection flagCollection = new ActiveUp.Net.Mail.FlagCollection();
                     flagCollection.Add("Answered\uFFFD");
                     if (mailbox1.Fetch.Flags(MessageId).Merged.ToLower().IndexOf("\\answered\uFFFD") == -1)
                         mailbox1.AddFlagsSilent(MessageId, flagCollection);
                 }
                 lConfirm.Text = ((Language)Session["language\uFFFD"]).Words[32].ToString() + " : <br /><br />\uFFFD" + message.To.Merged + message.Cc.Merged + message.Bcc.Merged.Replace(";\uFFFD", "<br />\uFFFD");
                 pForm.Visible = false;
                 pConfirm.Visible = true;
                 System.Web.HttpCookie httpCookie1 = new System.Web.HttpCookie("fromname\uFFFD", iFromName.Text);
                 System.Web.HttpCookie httpCookie2 = new System.Web.HttpCookie("fromemail\uFFFD", iFromEmail.Text);
                 System.Web.HttpCookie httpCookie3 = new System.Web.HttpCookie("replyto\uFFFD", iReplyTo.Text);
                 System.DateTime dateTime1 = System.DateTime.Now;
                 httpCookie1.Expires = dateTime1.AddMonths(2);
                 System.DateTime dateTime2 = System.DateTime.Now;
                 httpCookie2.Expires = dateTime2.AddMonths(2);
                 System.DateTime dateTime3 = System.DateTime.Now;
                 httpCookie3.Expires = dateTime3.AddMonths(2);
                 Response.Cookies.Add(httpCookie1);
                 Response.Cookies.Add(httpCookie2);
                 Response.Cookies.Add(httpCookie3);
                 if (cSave.Checked)
                 {
                     System.Web.HttpCookie httpCookie4 = new System.Web.HttpCookie("folder\uFFFD", dBoxes.SelectedItem.Text);
                     System.DateTime dateTime4 = System.DateTime.Now;
                     httpCookie4.Expires = dateTime4.AddMonths(2);
                     Response.Cookies.Add(httpCookie4);
                     ActiveUp.Net.Mail.Mailbox mailbox2 = ((ActiveUp.Net.Mail.Imap4Client)Session["imapobject\uFFFD"]).SelectMailbox(dBoxes.SelectedItem.Text);
                     mailbox2.Append(message.ToMimeString());
                 }
                 string[] sArr6 = System.IO.Directory.GetFiles(Page.Server.MapPath(Application["writedirectory\uFFFD"].ToString()));
                 for (int i4 = 0; i4 < sArr6.Length; i4++)
                 {
                     string s5 = sArr6[i4];
                     if (s5.IndexOf(Session.SessionID) != -1)
                         System.IO.File.Delete(s5);
                 }
             }
             catch (System.Exception e1)
             {
                 Page.RegisterStartupScript("ShowError\uFFFD", "<script>ShowErrorDialog('\uFFFD" + ((Language)Session["language\uFFFD"]).Words[83].ToString() + "','\uFFFD" + System.Text.RegularExpressions.Regex.Escape(e1.Message + e1.StackTrace).Replace("'\uFFFD", "\\'\uFFFD") + "');</script>\uFFFD");
             }
         }
         else
         {
             System.Web.HttpCookie httpCookie5 = new System.Web.HttpCookie("folder\uFFFD", dBoxes.SelectedItem.Text);
             System.DateTime dateTime5 = System.DateTime.Now;
             httpCookie5.Expires = dateTime5.AddMonths(2);
             Response.Cookies.Add(httpCookie5);
             ActiveUp.Net.Mail.Mailbox mailbox3 = ((ActiveUp.Net.Mail.Imap4Client)Session["imapobject\uFFFD"]).SelectMailbox(dBoxes.SelectedItem.Text);
             mailbox3.Append(message.ToMimeString());
         }
         string[] sArr8 = System.IO.Directory.GetFiles(Page.Server.MapPath(Application["writedirectory\uFFFD"].ToString()));
         for (int i5 = 0; i5 < sArr8.Length; i5++)
         {
             string s6 = sArr8[i5];
             if (s6.IndexOf(Session.SessionID) != -1)
                 System.IO.File.Delete(s6);
         }
     }
     catch (System.Exception e2)
     {
         Page.RegisterStartupScript("ShowError\uFFFD", "<script>ShowErrorDialog('\uFFFD" + ((Language)Session["language\uFFFD"]).Words[82].ToString() + "','\uFFFD" + System.Text.RegularExpressions.Regex.Escape(e2.Message + e2.StackTrace).Replace("'\uFFFD", "\\'\uFFFD") + "');</script>\uFFFD");
     }
 }
Exemple #42
0
 private string GetEncodedMimePart(MimePart part)
 {
     System.Text.StringBuilder sb = new System.Text.StringBuilder();
     try
     {
         sb.Append(part.ToMimeString());
         if (part.ContentTransferEncoding == ContentTransferEncoding.Base64) sb.Append("\r\n\r\n" + System.Text.RegularExpressions.Regex.Replace(System.Convert.ToBase64String(part.BinaryContent, 0, part.BinaryContent.Length), "(?<found>[^\n]{100})", "${found}\n"));
         else if (part.ContentTransferEncoding == ContentTransferEncoding.QuotedPrintable) sb.Append("\r\n\r\n" + Codec.ToQuotedPrintable(System.Text.Encoding.ASCII.GetString(part.BinaryContent, 0, part.BinaryContent.Length), part.Charset));
         else if (part.ContentTransferEncoding == ContentTransferEncoding.SevenBits) sb.Append("\r\n\r\n" + System.Text.Encoding.UTF7.GetString(part.BinaryContent, 0, part.BinaryContent.Length));
         else if (part.ContentTransferEncoding == ContentTransferEncoding.EightBits) sb.Append("\r\n\r\n" + System.Text.Encoding.UTF8.GetString(part.BinaryContent, 0, part.BinaryContent.Length));
         else sb.Append("\r\n\r\n" + System.Text.Encoding.ASCII.GetString(part.BinaryContent,0,part.BinaryContent.Length));
     }
     catch (System.Exception) { }
     return sb.ToString();
 }
Exemple #43
0
        public void AddAttachmentFromString(string filename, string body, Encoding encoding)
        {
            var decodedBytes = encoding.GetBytes(body);

            var textAttach = new MimePart(decodedBytes, filename, encoding.BodyName);

            Attachments.Add(textAttach);
        }
Exemple #44
0
        private MimePart GetMultipartRelatedContainer()
        {
            MimePart part = new MimePart();

            if (this.EmbeddedObjects.Count > 0)
            {
                part.ContentType.MimeType = "multipart/related";

                string unique = Codec.GetUniqueString();
                string boundary = "---AU_MimePart_" + unique;
                part.ContentType.Parameters.Add("boundary", boundary);

                part.ContentType.Parameters.Add("type", "\"multipart/alternative\"");

                part.SubParts.Add(this.GetBodiesPart());

                foreach (MimePart embeddedObject in this.EmbeddedObjects)
                    part.SubParts.Add(embeddedObject);
            }
            else part = this.GetBodiesPart();

            return part;
        }
Exemple #45
0
        private static void DispatchPart(MimePart part, ref Message message)
        {
            // This is a container part.
            if (part.SubParts.Count > 0)
            {
                DispatchParts(part, ref message);
            }
            // This is a leaf part.
            else
            {
                // If this part has to be displayed has an attachment, add it to the appropriate collection.
                if (part.ContentDisposition.Disposition.Equals("attachment"))
                {
                    message.Attachments.Add(part);
                }
                // If this part has to be displayed at the same time as the main body, add it to the appropriate collection.
                else if (part.ContentDisposition.Disposition.Equals("inline"))
                {
                    message.EmbeddedObjects.Add(part);
                }
                // Other parts are miscellaneous. How they are to be displayed is at the end-user's discretion.
                // Fix for avoid attach original mail message
                // Alberto --> introdotta una seconda clausola per evitare l'inserimento nelle unknown parts del testo della mail (in alcuni casi particolari)
                else if (!message.BodyText.ToMimePart().ContentTransferEncoding.Equals(part.ContentTransferEncoding) && !(part.ContentType.Type.Equals("text") && !part.ContentDisposition.Disposition.Equals("attachment")))
                {
                    // Alberto --> aggiunta clausola per evitare l'inserimento di mail negli attachment

                    if (!part.ContentType.MimeType.Equals("message/rfc822"))
                    {
                        message.UnknownDispositionMimeParts.Add(part);
                    }
                }

                // We will consider the highest-level text parts that are not attachments to be the intended for display.
                // We know the highest-level parts will be set, because the parser first goes to the deepest level and returns top-level parts last.
                if (part.ContentType.Type.Equals("text") && !part.ContentDisposition.Disposition.Equals("attachment"))
                {
                    if (part.ContentType.SubType.Equals("plain"))
                    {
                        message.BodyText.Charset = part.Charset;
                        message.BodyText.Text    = part.TextContent;
                    }
                    else if (part.ContentType.SubType.Equals("html"))
                    {
                        message.BodyHtml.Charset = part.Charset;
                        message.BodyHtml.Text    = part.TextContent;
                    }
                }

                // Parse message/rfc822 parts as Message objects and place them in the appropriate collection.
                // Alberto --> introdotta una reference al messaggio padre per migliorare la navigabilità
                if (part.ContentType.MimeType.Equals("message/rfc822"))
                {
                    Message innerMessage = Parser.ParseMessage(part.BinaryContent);
                    innerMessage.Container = message;
                    message.SubMessages.Add(innerMessage);
                }
                if (part.ContentType.MimeType.Equals("application/pkcs7-signature") ||
                    part.ContentType.MimeType.Equals("application/x-pkcs7-signature"))
                {
                    string toDigest = part.Container.TextContent;
                    //attenzione!!
                    //modificato Luigi
                    //index out of range
                    //toDigest = Regex.Split(toDigest, "\r\n--" + part.Container.ContentType.Parameters["boundary"])[1];
                    string[] yy = Regex.Split(toDigest, "\r\n--" + part.Container.ContentType.Parameters["boundary"]);
                    if (yy != null && yy.Length > 1)
                    {
                        toDigest = yy[1];
                    }
                    toDigest = toDigest.TrimStart('\r', '\n');
                    //Match endDelimiter = Regex.Match(toDigest, "(?<=[^\r\n]\r\n)\r\n", RegexOptions.RightToLeft);
                    //int lastNonNewLine = Regex.Match(toDigest, "[^\r\n]", RegexOptions.RightToLeft).Index;
                    //if (endDelimiter.Index != -1 && endDelimiter.Index > lastNonNewLine) toDigest = toDigest.Remove(endDelimiter.Index);

                    //TODO: What should be done in PPC ?
#if !PocketPC
                    message.Signatures.Smime = new SignedCms(new ContentInfo(Encoding.ASCII.GetBytes(toDigest)), true);
                    message.Signatures.Smime.Decode(part.BinaryContent);
#endif
                }

                // Anyway, this is a leaf part of the message.
                message.LeafMimeParts.Add(part);
            }
        }
Exemple #46
0
        /*public string GetBodies(string boundary)
		{
			System.Text.StringBuilder sb = new System.Text.StringBuilder();
			try
			{
				if((this.BodyHtml.Text!=null && this.BodyHtml.Text.Length>0) && (this.BodyText.Text!=null && this.BodyText.Text.Length>0))
				{
					sb.Append("--"+boundary);
					boundary = "---AU_MimePart_"+Codec.GetUniqueString();
					sb.Append("\r\nContent-Type: multipart/alternative;\r\n boundary=\""+boundary+"\"\r\n\r\n--"+boundary+"\r\nContent-Type: text/plain;\r\n charset=\""+this.BodyText.Charset+"\"\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n"+Codec.ToQuotedPrintable(this.BodyText.Text,this.BodyHtml.Charset));
					sb.Append("\r\n\r\n--"+boundary+"\r\nContent-Type: text/html;\r\n charset=\""+this.BodyHtml.Charset+"\"\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n"+Codec.ToQuotedPrintable(this.BodyHtml.Text,this.BodyHtml.Charset));
					sb.Append("\r\n\r\n--"+boundary+"--");
				}
				else if(this.BodyHtml.Text!=null && this.BodyHtml.Text.Length>0) sb.Append("--"+boundary+"\r\nContent-Type: text/html;\r\n charset=\""+this.BodyHtml.Charset+"\"\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n"+Codec.ToQuotedPrintable(this.BodyHtml.Text.TrimEnd('\n','\r'),this.BodyHtml.Charset));
				else if(this.BodyText.Text!=null && this.BodyText.Text.Length>0) sb.Append("--"+boundary+"\r\nContent-Type: text/plain;\r\n charset=\""+this.BodyText.Charset+"\"\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n"+Codec.ToQuotedPrintable(this.BodyText.Text.TrimEnd('\n','\r'),this.BodyText.Charset));
			} 
			catch(System.Exception) {  }
			return sb.ToString();
		}*/

        /// <summary>
        /// Converts a message to a message/rfc822 type MIME part, with a Content-Disposition set to "attachment".
        /// </summary>
        public MimePart ToMimePart()
        {
            MimePart part = new MimePart();
            try
            {
                part.Charset = this.Charset;
                part.ContentTransferEncoding = ContentTransferEncoding.SevenBits;
                part.ContentDisposition.Disposition = "attachment";
                part.ContentDisposition.FileName = this.Subject.Trim(' ').Replace(" ", "_") + ".eml";
                part.ContentType.MimeType = "message/rfc822";
                part.TextContent = this.ToMimeString();
            }
            catch (System.Exception) { }
            return part;
        }
Exemple #47
0
 /// <summary>
 /// Add a MimePart to the attachment collection.
 /// </summary>
 /// <param name="part"></param>
 public new void Add(MimePart part)
 {
     part.ContentDisposition.Disposition = "attachment";
     List.Add(part);
 }