This class provides a simplified way of parsing messages.
All the mime complexity is handled internally and all the content is exposed parsed and decoded. The code takes care of comments, RFC 2047, encodings, etc.
Ejemplo n.º 1
0
        public EmailMessageInfo ReadMessageStream(Stream stm, string attachmentDir)
        {
            SharpMessage sm = new SharpMessage(stm);

            EmailMessageInfo emi = new EmailMessageInfo();
            emi.From = sm.FromAddress;
            emi.Subject = sm.Subject;
            emi.BodyPlainText = sm.Body;
            List<string> lst = new List<string>();
            foreach (SharpMimeAddress addr in sm.To)
            {
                lst.Add(addr.ToString());
            }
            emi.To = lst.ToArray();
            lst = new List<string>();
            foreach (SharpMimeAddress addr in sm.Cc)
                lst.Add(addr.ToString());
            emi.Cc = lst.ToArray();
            emi.BodyText = sm.Body;
            foreach (SharpAttachment att in sm.Attachments)
            {
                if (!Directory.Exists(attachmentDir)) Directory.CreateDirectory(attachmentDir);
                AttachmentInfo ai = new AttachmentInfo();
                ai.Name = att.Name;
                string saveFile = Path.Combine(attachmentDir, att.Name);
                att.Save(saveFile, true);
                ai.FileName = saveFile;
                emi.Attachments.Add(ai);
            }

            foreach (object hdr in sm.Headers)
            {
            }
            return emi;
        }
Ejemplo n.º 2
0
        public SmtpEmail(SMTPMessage message)
        {
            this.message = message;
            header = new SmtpEmailHeader(message);

            var msg = new SharpMessage(new MemoryStream(Encoding.ASCII.GetBytes(message.Data)), SharpDecodeOptions.None);
            body = msg.Body.Trim();
        }
        public AlertMessage GetNextMessage()
        {
            FileInfo[] files;
            if ((files = newDir.GetFiles()).Length > 0)
            {
                files[0].MoveTo(Path.Combine(curDir.FullName, files[0].Name + ":2,"));
                SharpMessage message;
                using (FileStream stream = new FileStream(files[0].FullName, FileMode.Open))
                {
                    message = new SharpMessage(stream);
                }

                AlertMessage m = new AlertMessage();
                m.Date = message.Date;
                m.Subject = message.Subject;
                m.Body = message.Body;

                return m;
            }
            else
            {
                return null;
            }
        }
Ejemplo n.º 4
0
        public static void parse_msg(Lucene.Net.Index.IndexWriter writer, string docid, string msgtxt)
        {
            if (msgtxt.Length > 4 * 1024) {
                msgtxt = msgtxt.Substring(0, 4 * 1024 - 1);
            }
            // db.setValueParsed(".zdata/doc/" + docid, msgtxt);
            // gui.debugDump(db);

            if (true) {
                // sharptools
                SharpMessage msg = new anmar.SharpMimeTools.SharpMessage(msgtxt);
                System.Console.WriteLine("Subject: " + msg.Subject);
                var doc = new Lucene.Net.Documents.Document();
                doc.Add(new Field("body", msg.Body, Field.Store.YES, Field.Index.ANALYZED));
                doc.Add(new Field("docid", docid, Field.Store.YES, Field.Index.NOT_ANALYZED));
                writer.AddDocument(doc);
                // indexer.index_document(docid, msg.Body);
            }

            //foreach (SharpAttachment msgpart in msg.Attachments) {
            //    if (msgpart.MimeTopLevelMediaType == MimeTopLevelMediaType.text &&
            //        msgpart.MimeMediaSubType == "plain") {
            //        System.Console.WriteLine("Attachment: " + msgpart.Size);
            //   }
            //}
        }
        void HandlePgpMime(Outlook.MailItem mailItem, Microsoft.Office.Interop.Outlook.Attachment encryptedMime,
            Microsoft.Office.Interop.Outlook.Attachment sigMime, string sigHash = "sha1")
        {
            logger.Trace("> HandlePgpMime");
            CryptoContext Context = null;

            string sig = null;
            byte[] cyphertext = null;
            string cleartext = mailItem.Body;

            // 1. Decrypt attachement

            if (encryptedMime != null)
            {
                logger.Trace("Decrypting cypher text.");

            var tempfile = Path.GetTempFileName();
            encryptedMime.SaveAsFile(tempfile);
                cyphertext = File.ReadAllBytes(tempfile);
                File.Delete(tempfile);

                var clearbytes = DecryptAndVerify(mailItem.To, cyphertext, out Context);
                if (clearbytes == null)
                    return;

                cleartext = this._encoding.GetString(clearbytes);
            }

            // 2. Verify signature

            if (sigMime != null)
            {
                Context = new CryptoContext(Passphrase);
                var Crypto = new PgpCrypto(Context);
                Outlook.OlBodyFormat mailType = mailItem.BodyFormat;

                try
                {
                    logger.Trace("Verify detached signature");

                    var tempfile = Path.GetTempFileName();
                    sigMime.SaveAsFile(tempfile);
                    var detachedsig = File.ReadAllText(tempfile);
                    File.Delete(tempfile);

                    // Build up a clearsignature format for validation
                    // the rules for are the same with the addition of two heaer fields.
                    // Ultimately we need to get these fields out of email itself.

                    var encoding = GetEncodingFromMail(mailItem);

                    var clearsig = string.Format("-----BEGIN PGP SIGNED MESSAGE-----\r\nHash: {0}\r\n\r\n", sigHash);
                    //clearsig += "Content-Type: text/plain; charset=ISO-8859-1\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n";
                    clearsig += "Content-Type: text/plain; charset=" +
                        encoding.BodyName.ToUpper()+
                        "\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n";

                    clearsig += PgpClearDashEscapeAndQuoteEncode(
                        encoding.GetString(
                        (byte[])mailItem.PropertyAccessor.GetProperty(
                            "http://schemas.microsoft.com/mapi/string/{4E3A7680-B77A-11D0-9DA5-00C04FD65685}/Internet Charset Body/0x00000102")));

                    clearsig += "\r\n"+detachedsig;

                    logger.Trace(clearsig);

                    if (Crypto.VerifyClear(_encoding.GetBytes(clearsig)))
                    {
                        Context = Crypto.Context;

                        var message = "** Valid signature from \"" + Context.SignedByUserId +
                            "\" with KeyId " + Context.SignedByKeyId + ".\n\n";

                        if (mailType == Outlook.OlBodyFormat.olFormatPlain)
                        {
                            mailItem.Body = message + mailItem.Body;
                        }
                    }
                    else
                    {
                        Context = Crypto.Context;

                        var message = "** Invalid signature from \"" + Context.SignedByUserId +
                            "\" with KeyId " + Context.SignedByKeyId + ".\n\n";

                        if (mailType == Outlook.OlBodyFormat.olFormatPlain)
                        {
                            mailItem.Body = message + mailItem.Body;
                        }
                    }
                }
                catch (PublicKeyNotFoundException ex)
                {
                    logger.Debug(ex.ToString());

                    Context = Crypto.Context;

                    var message = "** Unable to verify signature, missing public key.\n\n";

                    if (mailType == Outlook.OlBodyFormat.olFormatPlain)
                    {
                        mailItem.Body = message + mailItem.Body;
                    }
                }
                catch (Exception ex)
                {
                    logger.Debug(ex.ToString());

                    this.Passphrase = null;

                    WriteErrorData("VerifyEmail", ex);
                    MessageBox.Show(
                        ex.Message,
                        "Outlook Privacy Error",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                }

                return;

            }

            if (Context == null)
                return;

            // Extract files from MIME data

            SharpMessage msg = new SharpMessage(cleartext);
            string body = mailItem.Body;

            var DecryptAndVerifyHeaderMessage = "** ";

            if (Context.IsEncrypted)
                DecryptAndVerifyHeaderMessage += "Message decrypted. ";

            if (Context.FailedIntegrityCheck)
                DecryptAndVerifyHeaderMessage += "Failed integrity check! ";

            if (Context.IsSigned && Context.SignatureValidated)
            {
                DecryptAndVerifyHeaderMessage += "Valid signature from \"" + Context.SignedByUserId +
                    "\" with KeyId " + Context.SignedByKeyId;
            }
            else if (Context.IsSigned)
            {
                DecryptAndVerifyHeaderMessage += "Invalid signature from \"" + Context.SignedByUserId +
                    "\" with KeyId " + Context.SignedByKeyId + ".";
            }
            else
                DecryptAndVerifyHeaderMessage += "Message was unsigned.";

            DecryptAndVerifyHeaderMessage += "\n\n";

            if (mailItem.BodyFormat == Outlook.OlBodyFormat.olFormatPlain)
            {
                mailItem.Body = DecryptAndVerifyHeaderMessage + msg.Body;
            }
            else if (mailItem.BodyFormat == Outlook.OlBodyFormat.olFormatHTML)
            {
                if (!msg.Body.TrimStart().ToLower().StartsWith("<html"))
                {
                    body = DecryptAndVerifyHeaderMessage + msg.Body;
                    body = System.Net.WebUtility.HtmlEncode(body);
                    body = body.Replace("\n", "<br />");

                    mailItem.HTMLBody = "<html><head></head><body>" + body + "</body></html>";
                }
                else
                {
                    // Find <body> tag and insert our message.

                    var matches = Regex.Match(msg.Body, @"(<body[^<]*>)", RegexOptions.IgnoreCase);
                    if (matches.Success)
                    {
                        var bodyTag = matches.Groups[1].Value;

                        // Insert decryption message.
                        mailItem.HTMLBody = msg.Body.Replace(
                            bodyTag,
                            bodyTag + DecryptAndVerifyHeaderMessage.Replace("\n", "<br />"));
                    }
                    else
                        mailItem.HTMLBody = msg.Body;
                }
            }
            else
            {
                // May cause mail item not to open correctly

                mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatPlain;
                mailItem.Body = msg.Body;
            }

            foreach (SharpAttachment mimeAttachment in msg.Attachments)
            {
                mimeAttachment.Stream.Position = 0;
                var fileName = mimeAttachment.Name;
                var tempFile = Path.Combine(Path.GetTempPath(), fileName);

                using (FileStream fout = File.OpenWrite(tempFile))
                {
                    mimeAttachment.Stream.CopyTo(fout);
                }

                mailItem.Attachments.Add(tempFile, Outlook.OlAttachmentType.olByValue, 1, fileName);
            }

            //mailItem.Save();
        }
Ejemplo n.º 6
0
        public void parse_msg(LayerWriteGroup txwg, string docid, string msgtxt, out int numwords)
        {
            if (msgtxt.Length > 4 * 1024) {
                msgtxt = msgtxt.Substring(0, 4 * 1024 - 1);
            }
            // db.setValueParsed(".zdata/doc/" + docid, msgtxt);
            // gui.debugDump(db);

            #if true
                // sharptools
                SharpMessage msg = new anmar.SharpMimeTools.SharpMessage(msgtxt);
                System.Console.WriteLine("Subject: " + msg.Subject);

                indexer.index_document(txwg, docid, msg.Body, out numwords);
            #else
                // LumiSoft
                Mime msg = LumiSoft.Net.Mime.Mime.Parse(System.Text.Encoding.Default.GetBytes(msgtxt));
                System.Console.WriteLine("Subject: " + msg.MainEntity.Subject);
                indexer.index_document(txwg, docid, msg.MainEntity.DataText, out numwords);
            #endif

            //foreach (SharpAttachment msgpart in msg.Attachments) {
            //    if (msgpart.MimeTopLevelMediaType == MimeTopLevelMediaType.text &&
            //        msgpart.MimeMediaSubType == "plain") {
            //        System.Console.WriteLine("Attachment: " + msgpart.Size);
            //   }
            //}
        }
        void HandlePgpMime(Outlook.MailItem mailItem, Microsoft.Office.Interop.Outlook.Attachment encryptedMime)
        {
            // 1. Decrypt attachement

            CryptoContext Context;
            var tempfile = Path.GetTempFileName();
            encryptedMime.SaveAsFile(tempfile);
            var encrypteddata = File.ReadAllBytes(tempfile);
            var cleardata = DecryptAndVerify(mailItem.To, encrypteddata, out Context);
            if (cleardata == null)
                return;

            // Extract files from MIME data

            SharpMessage msg = new SharpMessage(this._encoding.GetString(cleardata));
            string body = mailItem.Body;

            var DecryptAndVerifyHeaderMessage = "** ";

            if (Context.IsEncrypted)
                DecryptAndVerifyHeaderMessage += "Message decrypted. ";

            if (Context.IsSigned && Context.SignatureValidated)
            {
                DecryptAndVerifyHeaderMessage += "Valid signature from \"" + Context.SignedByUserId +
                    "\" with KeyId " + Context.SignedByKeyId;
            }
            else if (Context.IsSigned)
            {
                DecryptAndVerifyHeaderMessage += "Invalid signature from \"" + Context.SignedByUserId +
                    "\" with KeyId " + Context.SignedByKeyId + ".";
            }
            else
                DecryptAndVerifyHeaderMessage += "Message was unsigned.";

            DecryptAndVerifyHeaderMessage += "\n\n";

            if (mailItem.BodyFormat == Outlook.OlBodyFormat.olFormatPlain)
            {
                mailItem.Body = DecryptAndVerifyHeaderMessage + msg.Body;
            }
            else if (mailItem.BodyFormat == Outlook.OlBodyFormat.olFormatHTML)
            {
                if (!msg.Body.TrimStart().ToLower().StartsWith("<html"))
                {
                    body = DecryptAndVerifyHeaderMessage + msg.Body;
                    body = System.Net.WebUtility.HtmlEncode(body);
                    body = body.Replace("\n", "<br />");

                    mailItem.HTMLBody = "<html><head></head><body>" + body + "</body></html>";
                }
                else
                {
                    // Find <body> tag and insert our message.

                    var matches = Regex.Match(msg.Body, @"(<body[^<]*>)", RegexOptions.IgnoreCase);
                    if (matches.Success)
                    {
                        var bodyTag = matches.Groups[1].Value;

                        // Insert decryption message.
                        mailItem.HTMLBody = msg.Body.Replace(
                            bodyTag,
                            bodyTag + DecryptAndVerifyHeaderMessage.Replace("\n", "<br />"));
                    }
                    else
                        mailItem.HTMLBody = msg.Body;
                }
            }
            else
            {
                // May cause mail item not to open correctly

                mailItem.BodyFormat = Outlook.OlBodyFormat.olFormatPlain;
                mailItem.Body = msg.Body;
            }

            foreach (SharpAttachment mimeAttachment in msg.Attachments)
            {
                mimeAttachment.Stream.Position = 0;
                var fileName = mimeAttachment.Name;
                var tempFile = Path.Combine(Path.GetTempPath(), fileName);

                using (FileStream fout = File.OpenWrite(tempFile))
                {
                    mimeAttachment.Stream.CopyTo(fout);
                }

                mailItem.Attachments.Add(tempFile, Outlook.OlAttachmentType.olByValue, 1, fileName);
            }

            //mailItem.Save();
        }