Пример #1
0
        // Convert all .msg files to plain text
        public void toPlainText(OutlookStorage.Message outlookMsg, string path, string filename)
        {
            System.IO.StreamWriter file = new System.IO.StreamWriter(path + filename + ".txt", true);
            //this.textBox1.Text += "Message " + filename + " copied to\n\r\n\r\t" + path + "\n\r\n\r";
            form1.appendTextBox1("Message " + filename + "\n\r");
            file.WriteLine("Subject: {0}", outlookMsg.Subject);
            file.WriteLine("Body: {0}", outlookMsg.BodyText);

            file.WriteLine("{0} Recipients", outlookMsg.Recipients.Count);
            foreach (OutlookStorage.Recipient recip in outlookMsg.Recipients)
            {
                file.WriteLine(" {0}:{1}", recip.Type, recip.Email);
            }

            file.WriteLine("{0} Attachments", outlookMsg.Attachments.Count);
            foreach (OutlookStorage.Attachment attach in outlookMsg.Attachments)
            {
                file.WriteLine(" {0}, {1}b", attach.Filename, attach.Data.Length);
            }

            file.WriteLine("{0} Messages", outlookMsg.Messages.Count);
            foreach (OutlookStorage.Message subMessage in outlookMsg.Messages)
            {
                int msgSub = 1;
                toPlainText(subMessage, path, filename + "_sub_" + msgSub);
                form1.appendTextBox1("Sub-Message of " + filename + "\n\r");
            }
            file.Close();
        }
Пример #2
0
        // Copy Files to Temp Directory at targetPath
        private void CopyFiles(String[] filenames, MemoryStream[] filestreams)
        {
            string filename;

            for (int fileIndex = 0; fileIndex < filenames.Length; fileIndex++)
            {
                //use the fileindex to get the name and data stream
                filename = filenames[fileIndex];
                MemoryStream filestream = filestreams[fileIndex];

                //save the file stream using its name to the application path
                FileStream outputStream = File.Create(filename);
                filestream.WriteTo(outputStream);
                outputStream.Close();

                //Generate new Files
                //Create new Outlook Message object from filename
                OutlookStorage.Message outlookMsg = new OutlookStorage.Message(filename);

                //Save the message as a text file to target path
                toPlainText(outlookMsg, this.targetPath, filename.Substring(0, filename.Length - 4));

                //Save each attachment to target path
                foreach (OutlookStorage.Attachment attach in outlookMsg.Attachments)
                {
                    byte[]     attachBytes  = attach.Data;
                    FileStream attachStream = File.Create(this.targetPath + attach.Filename);
                    attachStream.Write(attachBytes, 0, attachBytes.Length);
                    attachStream.Close();
                    form1.appendTextBox1("Attachment " + attach.Filename + "\n\r");
                }
                filestream.Close();
            }
        }
Пример #3
0
 /// <summary>
 /// Adds attachments for a message
 /// </summary>
 /// <param name="message"></param>
 private void AddAttachments(OutlookStorage.Message message)
 {
     foreach (OutlookStorage.Attachment attachment in message.Attachments)
     {
         attachments.AppendText(attachment.Filename + ": " + attachment.Data.Length + "b\r\n\r\n");
     }
 }
Пример #4
0
 public void InsertMailItem(OutlookStorage.Message message)
 {
     try
     {
         using (SPSite site = new SPSite(ConfigurationManager.AppSettings["siteUrl"]))
         {
             using (SPWeb web = site.OpenWeb())
             {
                 if (web.Lists[ConfigurationManager.AppSettings["listName"]] == null)
                 {
                     createList();
                 }
                 SPListItem newMailListItem = new web.Lists["Incoming Mail List"].AddItem();
                 newMailListItem["Title"]  = message.Subject;
                 newMailListItem["Body"]   = message.BodyText;
                 newMailListItem["Sender"] = new SPFieldUserValue(web, message.From);
                 newMailListItem.update();
                 foreach (OutlookStorage.Attachment attach in message.Attachments)
                 {
                     byte[]     attachBytes  = attach.Data;
                     FileStream attachStream = File.Create(attach.Filename);
                     attachStream.Write(attachBytes, 0, attachBytes.Length);
                     attachStream.Close();
                     newMailListItem.Attachments.Add(attach.Filename, attachBytes);
                     newMailListItem.update();
                 }
             }
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Пример #5
0
 /// <summary>
 /// Populates the extended data for a message
 /// </summary>
 /// <param name="message"></param>
 private void PopulateData(OutlookStorage.Message message)
 {
     data.Text = "";
     foreach (string key in message.streamStatistics.Keys)
     {
         string hexKey = key.Substring(12, 4);
         try
         {
             object property = message.GetMapiProperty(hexKey);
             if (property == null)
             {
                 data.AppendText((string.Format("Key {0} is null{1}", hexKey, Environment.NewLine)));
             }
             else if (property is byte[])
             {
                 data.AppendText(string.Format("Key {0} is a byte array{1}", hexKey, Environment.NewLine));
             }
             else
             {
                 data.AppendText(string.Format("{0}: {1}{2}", hexKey, property.ToString(), Environment.NewLine));
             }
         }
         catch
         {
             data.AppendText(string.Format("Key {0} threw an exception{1}", hexKey, Environment.NewLine));
         }
     }
 }
Пример #6
0
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Filter      = "Outlook Message Mail (.msg)|*.msg";
            ofd.FilterIndex = 1;

            ofd.Multiselect = true;

            // Process input if the user clicked OK.
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                foreach (String file in ofd.FileNames)
                {
                    OutlookStorage.Message newMessage = new OutlookStorage.Message(file);
                    messages.Add(newMessage);
                }
            }
            listBox1.DataSource = null;
            listBox1.DataSource = messages;

            try
            {
                listBox1.SelectedIndex = 0;
            }
            catch (Exception)
            {
            }
        }
Пример #7
0
    // Email

    public static int storeEmail(int collectionId, int userId, int classId, string emailName)
    {
        Stream messageStream = File.Open(emailName, FileMode.Open, FileAccess.Read);

        OutlookStorage.Message message = new OutlookStorage.Message(messageStream);
        messageStream.Close();

        int id = insertEmail(
            emailName,
            collectionId,
            userId,
            classId,
            message.ReceivedOrSentTime.ToString(),
            message.Subject,
            message.BodyText
            );

        storeEmailParticipant(id, message.FromAddress, "From");
        foreach (string p in parseAddresses(message.Recipients, OutlookStorage.RecipientType.To))
        {
            storeEmailParticipant(id, p, "To");
        }
        foreach (string p in parseAddresses(message.Recipients, OutlookStorage.RecipientType.CC))
        {
            storeEmailParticipant(id, p, "Cc");
        }

        return(id);
    }
 public static void ReadOutlookMail(string filepath)
 {
     try
     {
         OutlookStorage.Message outlookMsg = new OutlookStorage.Message(filepath);
         new SPOperations().InsertMailItem(outlookMsg);
         //SaveMessage(outlookMsg);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Пример #9
0
 public static void ProcessMsgList(string[] files)
 {
     foreach (string filename in files)
     {
         if (IsMsgFile(filename))
         {
             OutlookStorage.Message message = new OutlookStorage.Message(filename);
             DateTime date = message.ReceivedOrSentTime;
             message.Dispose();
             AddDateToMsgName(filename, date);
         }
     }
 }
Пример #10
0
        private void ReadMsgFile(string msgfile)
        {
            //清空附件内容列表,删除附件菜单项
            MailBody = string.Empty;
            Attachments.Clear();
            btnFiles.DropDownItems.Clear();
            lblStatus.Text = "-";

            FileInfo fi = new FileInfo(msgfile);

            this.Text = string.Format("EmailViewer of {0}", fi.Name);
            using (Stream messageStream = File.Open(msgfile, FileMode.Open, FileAccess.Read))
            {
                //fileName = string.Empty;
                OutlookStorage.Message message = new OutlookStorage.Message(messageStream);
                messageStream.Close();
                try
                {
                    //获取comment#
                    //Comment has been added as: 34227
                    //string comment = null;
                    MailBody          = message.BodyText;
                    this.txtMail.Text = MailBody;

                    //附件
                    if (message.Attachments.Count > 0)
                    {
                        int i = 0;
                        foreach (OutlookStorage.Attachment item in message.Attachments)
                        {
                            string fileContent = System.Text.Encoding.UTF8.GetString(item.Data);
                            Attachments.Add(fileContent);
                            ToolStripMenuItem ddItem = new ToolStripMenuItem(item.Filename);
                            ddItem.Name   = "btnFile" + i.ToString();
                            ddItem.Width  = 300;
                            ddItem.Click += ddItem_Click;
                            btnFiles.DropDownItems.Add(ddItem);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "不好,出了点儿问题", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    message.Dispose();
                }
            }
        }
        private static void SaveMessage(OutlookStorage.Message outlookMsg)
        {
            outlookMsg.Save(outlookMsg.Subject.Replace(":", ""));

            foreach (OutlookStorage.Attachment attach in outlookMsg.Attachments)
            {
                byte[]     attachBytes  = attach.Data;
                FileStream attachStream = File.Create(attach.Filename);
                attachStream.Write(attachBytes, 0, attachBytes.Length);
                attachStream.Close();
            }

            foreach (OutlookStorage.Message subMessage in outlookMsg.Messages)
            {
                SaveMessage(subMessage);
            }
        }
Пример #12
0
 /// <summary>
 /// Adds recipients for a message
 /// </summary>
 /// <param name="message"></param>
 private void AddRecipients(OutlookStorage.Message message)
 {
     to.Text = "";
     cc.Text = "";
     foreach (OutlookStorage.Recipient recipient in message.Recipients)
     {
         if (recipient.Type == OutlookStorage.RecipientType.To)
         {
             to.AppendText(recipient.Email + ", ");
         }
         else if (recipient.Type == OutlookStorage.RecipientType.CC)
         {
             cc.AppendText(recipient.Email + ", ");
         }
     }
     to.Text = to.Text.TrimEnd().TrimEnd(',');
     cc.Text = cc.Text.TrimEnd().TrimEnd(',');
 }
Пример #13
0
        private void readFile(String filename)
        {
            txtBox.Clear();
            treeView.Nodes.Clear();
            Stream messageStream = File.Open(filename, FileMode.Open, FileAccess.Read);

            OutlookStorage.Message message = new OutlookStorage.Message(messageStream);
            messageStream.Close();
            if (!isOutlookMessage(message))
            {
                MessageBox.Show("No Outlook MSG file!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                message.Dispose();
                return;
            }
            smimefound = false;
            this.loadMessage(message, treeView.Nodes.Add("Message"));
            message.Dispose();
            mnuExport.Enabled = true;
            treeView.ExpandAll();
            txtBox.SelectionStart  = 0;
            txtBox.SelectionLength = 0;
            copyContentToClipboardToolStripMenuItem.Enabled = true;
        }
Пример #14
0
        /// <summary>
        /// Load an individual email
        /// </summary>
        /// <param name="path"></param>
        private void LoadMessage(string path)
        {
            // open a message stream to get the message object
            Stream messageStream = File.Open(path, FileMode.Open, FileAccess.Read);

            OutlookStorage.Message message = new OutlookStorage.Message(messageStream);
            messageStream.Close();

            // set the basic properties
            body.Rtf     = message.BodyRTF;
            subject.Text = message.Subject;
            from.Text    = string.Format("{0} <{1}>", message.From, message.GetMapiPropertyString("5D01"));
            headers.Text = message.GetMapiPropertyString("007D");

            // add the recipients
            AddRecipients(message);

            // add any attachments
            AddAttachments(message);

            // populate the extended data
            PopulateData(message);
        }
Пример #15
0
        private void btnDump_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.Multiselect = true;
            DialogResult msgFileSelectResult = this.openFileDialog1.ShowDialog();

            if (msgFileSelectResult == DialogResult.OK)
            {
                string targetFolder = this.openFileDialog1.FileNames[0];
                targetFolder = System.IO.Directory.GetParent(targetFolder).FullName;
                foreach (string msgfile in this.openFileDialog1.FileNames)
                {
                    bool   attachGenerated = false;
                    string fileName        = null;
                    using (Stream messageStream = File.Open(msgfile, FileMode.Open, FileAccess.Read))
                    {
                        fileName = string.Empty;
                        OutlookStorage.Message message = new OutlookStorage.Message(messageStream);
                        messageStream.Close();
                        try
                        {
                            //获取comment#
                            //Comment has been added as: 34227
                            string comment = null;
                            string body    = message.BodyText;
                            comment = body.Substring(body.IndexOf("Comment has been added as:") + 26).Trim();
                            //Insurer: Aggressive Insurance Texas Elite
                            string insurer = null;
                            string state   = null;
                            string title   = message.Subject;
                            if (title.Contains("Reminder Email for debugging purpose"))
                            {
                                //CarrierName: Progressive Auto
                                insurer = ExtractHtml(body, "CarrierName:", "\r\n");
                                if (string.IsNullOrEmpty(insurer))
                                {
                                    throw new Exception("Failed to extract CarrierName");
                                }
                                insurer = insurer.Trim().Split(' ')[0];
                                //Quoting State: VT
                                state = body.Substring(body.IndexOf("Quoting State:") + 14).Trim();
                                state = state.Substring(0, state.IndexOf("\r\n"));
                            }
                            else
                            {
                                //insurer = body.Substring(body.IndexOf("Insurer:")+8).Trim();
                                //insurer = insurer.Substring(0, insurer.IndexOf("\r\n"));
                                //insurer = insurer.Substring(0, insurer.IndexOf(" "));
                                //qpquote\stdInsurers\HartfordScrape.vb
                                insurer = body.Substring(body.LastIndexOf("qpquote\\stdInsurers\\") + 20);
                                if (insurer.Contains(".vb"))
                                {
                                    insurer = insurer.Substring(0, insurer.IndexOf(".vb"));
                                    if (insurer.Contains("Scrape"))
                                    {
                                        //insurer = insurer.Replace("Scrape", "");
                                        insurer = insurer.Substring(0, insurer.IndexOf("Scrape"));
                                    }
                                }
                                else
                                {
                                    //Insurer: Progressive Insurance Company
                                    insurer = ExtractHtml(insurer, "Insurer:", "Insurer Web Login:"******"Failed to extract Insurer Company Name");
                                    }
                                    insurer = insurer.Trim().Split(' ')[0];
                                }
                                //State Quoted: MA

                                state = body.Substring(body.IndexOf("State Quoted:") + 13).Trim();
                                state = state.Substring(0, state.IndexOf("\r\n"));
                            }
                            //2017-08-10,iimax:state rule changed
                            if (state.StartsWith("State"))
                            {
                                state = state.Substring(5);
                            }
                            fileName = string.Format("#{0}-{1} ({2}).txt", comment, insurer, state);
                            //附件
                            if (message.Attachments.Count > 0)
                            {
                                OutlookStorage.Attachment file = message.Attachments[0];
                                string fileContent             = System.Text.Encoding.UTF8.GetString(file.Data);
                                //2016-06-29:修改last name为 testing,修改 effdate
                                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                                doc.PreserveWhitespace = true;
                                doc.LoadXml(fileContent);
                                if (fileContent.Contains("<AutoQuote>"))
                                {
                                    var CusLastName = doc.DocumentElement.SelectSingleNode("/AutoQuote/Quotation/CusLastName");
                                    if (CusLastName != null)
                                    {
                                        //Create a comment.
                                        XmlComment newComment = doc.CreateComment(CusLastName.OuterXml);
                                        CusLastName.ParentNode.InsertAfter(newComment, CusLastName);
                                        CusLastName.InnerText = "Testing";
                                    }
                                    var EffDate = doc.DocumentElement.SelectSingleNode("/AutoQuote/Quotation/EffDate");
                                    if (EffDate != null)
                                    {
                                        string   eff = EffDate.InnerText;
                                        DateTime dt  = DateTime.Today;
                                        DateTime.TryParse(eff, out dt);
                                        if (dt < DateTime.Today)
                                        {
                                            XmlComment newComment = doc.CreateComment(EffDate.OuterXml);
                                            EffDate.ParentNode.InsertAfter(newComment, EffDate);
                                            EffDate.InnerText = DateTime.Today.ToString("MM/dd/yyyy");
                                        }
                                    }
                                    var drivers = doc.DocumentElement.SelectNodes("/AutoQuote/Quotation/Drivers/Driver");
                                    if (drivers != null)
                                    {
                                        foreach (XmlNode item in drivers)
                                        {
                                            var LastName = item.SelectSingleNode("LastName");
                                            if (LastName != null)
                                            {
                                                XmlComment newComment = doc.CreateComment(LastName.OuterXml);
                                                LastName.ParentNode.InsertAfter(newComment, LastName);
                                                LastName.InnerText = "Testing";
                                            }
                                        }
                                    }
                                }
                                else if (fileContent.Contains("<HomeQuote>"))
                                {
                                    var CusLastName = doc.DocumentElement.SelectSingleNode("/HomeQuote/InsuredInfo/CusLastName");
                                    if (CusLastName != null)
                                    {
                                        //Create a comment.
                                        XmlComment newComment = doc.CreateComment(CusLastName.OuterXml);
                                        CusLastName.ParentNode.InsertAfter(newComment, CusLastName);
                                        CusLastName.InnerText = "Testing";
                                    }
                                    var hEffDate = doc.DocumentElement.SelectSingleNode("/HomeQuote/InsuredInfo/hEffDate");
                                    if (hEffDate != null)
                                    {
                                        string   eff = hEffDate.InnerText;
                                        DateTime dt  = DateTime.Today;
                                        if (DateTime.TryParse(eff, out dt))
                                        {
                                        }
                                        if (dt < DateTime.Today)
                                        {
                                            XmlComment newComment = doc.CreateComment(hEffDate.OuterXml);
                                            hEffDate.ParentNode.InsertAfter(newComment, hEffDate);
                                            hEffDate.InnerText = DateTime.Today.ToString("MM/dd/yyyy");

                                            var hExpDate = doc.DocumentElement.SelectSingleNode("/HomeQuote/InsuredInfo/hExpDate");
                                            if (hExpDate != null)
                                            {
                                                XmlComment hExpDateComment = doc.CreateComment(hExpDate.OuterXml);
                                                hExpDate.ParentNode.InsertAfter(hExpDateComment, hExpDate);
                                                hExpDate.InnerText = DateTime.Today.AddYears(1).ToString("MM/dd/yyyy");
                                            }
                                            //修改 RiskInfo
                                            var EffDate = doc.DocumentElement.SelectSingleNode("/HomeQuote/RiskInfo/ThisRisk/EffDate");
                                            var ExpDate = doc.DocumentElement.SelectSingleNode("/HomeQuote/RiskInfo/ThisRisk/ExpDate");
                                            if (EffDate != null)
                                            {
                                                XmlComment xComment = doc.CreateComment(EffDate.OuterXml);
                                                EffDate.ParentNode.InsertAfter(xComment, EffDate);
                                                EffDate.InnerText = DateTime.Today.ToString("MM/dd/yyyy");
                                            }

                                            if (ExpDate != null)
                                            {
                                                XmlComment xComment = doc.CreateComment(ExpDate.OuterXml);
                                                ExpDate.ParentNode.InsertAfter(xComment, ExpDate);
                                                ExpDate.InnerText = DateTime.Today.AddYears(1).ToString("MM/dd/yyyy");
                                            }
                                        }
                                    }
                                }
                                fileContent = doc.OuterXml;
                                System.IO.File.WriteAllText(Path.Combine(targetFolder, fileName), fileContent);
                            }
                            attachGenerated = true;
                            //MessageBox.Show(fileName);
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                        finally
                        {
                            message.Dispose();
                        }

                        if (attachGenerated)
                        {
                            //重命名msg
                            FileInfo fi = new FileInfo(msgfile);
                            //目标文件名
                            string msgfileName = fi.Name;
                            string ourfileName = fi.Name.Replace(".msg", string.Format("{0}.msg", fileName));
                            ourfileName = ourfileName.Replace("comment#", "#").Replace(".txt.", ".");
                            System.IO.File.Move(msgfile, Path.Combine(fi.DirectoryName, ourfileName));
                        }
                    }
                }
            }
        }
Пример #16
0
        private void ReadMsgFile(string msgfile)
        {
            MessageFile = msgfile;
            //清空附件内容列表,删除附件菜单项
            MailBody = string.Empty;
            Attachments.Clear();
            btnFiles.DropDownItems.Clear();
            lblStatus.Text = "-";

            FileInfo fi = new FileInfo(msgfile);

            this.Text = string.Format("EmailViewer of {0}", fi.Name);
            try
            {
                using (Stream messageStream = File.Open(msgfile, FileMode.Open, FileAccess.Read))
                {
                    //fileName = string.Empty;
                    OutlookStorage.Message message = new OutlookStorage.Message(messageStream);
                    messageStream.Close();
                    try
                    {
                        //获取comment#
                        //Comment has been added as: 34227
                        //string comment = null;
                        MailBody = message.BodyRTF;

                        //附件
                        string attachments = "";
                        if (message.Attachments.Count > 0)
                        {
                            int i = 0;
                            foreach (OutlookStorage.Attachment item in message.Attachments)
                            {
                                //string fileContent = System.Text.Encoding.UTF8.GetString(item.Data);
                                Attachments.Add(i);
                                ToolStripMenuItem ddItem = new ToolStripMenuItem(item.Filename);
                                ddItem.Name   = "btnFile" + i.ToString();
                                ddItem.Width  = 300;
                                ddItem.Click += ddItem_Click;
                                btnFiles.DropDownItems.Add(ddItem);

                                attachments += String.Format("\t{0}{1}", item.Filename, Environment.NewLine);
                            }
                        }
                        string recipients = "";
                        foreach (OutlookStorage.Recipient recipeint in message.Recipients)
                        {
                            recipients += String.Format("\t{0} <{1}>{2}", recipeint.DisplayName, recipeint.Email, Environment.NewLine);
                        }

                        MessageMetadata = String.Format(@"Filename: {4}
Subject: {0}
From: {1}
Recipients: 
{2}
Attachments: 
{3}", message.Subject, message.From, recipients, attachments, fi.Name);

                        this.txtMail.Rtf = MailBody;
                    }
                    catch (IOException ex)
                    {
                        MessageBox.Show(ex.Message, "Exeception opening the email!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        message.Dispose();
                    }
                }
            } catch (IOException ex)
            {
                MessageBox.Show(ex.Message, "Couldn't open file", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Пример #17
0
        void ddItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem ddItem = sender as ToolStripMenuItem;

            if (ddItem == null)
            {
                return;
            }
            string btnName = ddItem.Name;
            int    idx     = ddItem.Name.IndexOf("btnFile");

            if (idx == -1)
            {
                lblStatus.Text = "Error";
                return;
            }
            string AttachIndex = ddItem.Name.Substring(idx + 7);
            int?   index       = ToInt(AttachIndex);

            if (index.HasValue && MessageFile != null)
            {
                int attachmentNum = Attachments[index.Value];
                try
                {
                    using (Stream messageStream = File.Open(MessageFile, FileMode.Open, FileAccess.Read))
                    {
                        //fileName = string.Empty;
                        OutlookStorage.Message message = null;
                        try
                        {
                            message = new OutlookStorage.Message(messageStream);
                            //messageStream.Close();

                            int i = 0;
                            OutlookStorage.Attachment attachment = null;
                            foreach (OutlookStorage.Attachment attachment_ in message.Attachments)
                            {
                                if (i == attachmentNum)
                                {
                                    attachment = attachment_;
                                    break;
                                }
                            }
                            if (attachment == null)
                            {
                                MessageBox.Show("Something has gone terribly wrong in opening this attachment (can't find it attached anymore)");
                                return;
                            }
                            string filename = String.Format("{0}{1}{2}", TempPath, Path.DirectorySeparatorChar, attachment.Filename);
                            using (FileStream f = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write))
                            {
                                Task t = f.WriteAsync(attachment.Data, 0, attachment.Data.Length);
                                t.ContinueWith((prevTask) =>
                                {
                                    System.Diagnostics.Process.Start(filename);
                                });
                            }
                        }
                        finally
                        {
                            if (message != null)
                            {
                                message.Dispose();
                            }
                        }
                    }
                }catch (IOException ex)
                {
                    Console.WriteLine("ex", ex.Message);
                }
            }
            else
            {
                lblStatus.Text = "Error";
            }
        }
Пример #18
0
        private void loadMessage(OutlookStorage.Message message, TreeNode messageNode)
        {
            String str;

            str = "Outlook Envelope data";
            messageNode.Text = str;
            txtBox.AppendText(str + "\n");


            str = message.Subject;
            messageNode.Nodes.Add(str);
            txtBox.AppendText(str + "\n");

            str = "Subject: " + message.Subject;
            messageNode.Nodes.Add(str);
            txtBox.AppendText(str + "\n");


            /*TreeNode bodyNode = messageNode.Nodes.Add("Body: (double click to view)");
             * bodyNode.Tag = new string[] { message.BodyText, message.BodyRTF };
             */
            str = "Recipients: " + message.Recipients.Count;
            TreeNode recipientNode = messageNode.Nodes.Add(str);

            txtBox.AppendText(str + "\n");
            foreach (OutlookStorage.Recipient recipient in message.Recipients)
            {
                str = recipient.Type + ": " + recipient.Email;
                recipientNode.Nodes.Add(str);
                txtBox.AppendText(str + "\n");
            }

            str = "Attachments: " + message.Attachments.Count;
            TreeNode attachmentNode = messageNode.Nodes.Add(str);

            txtBox.AppendText(str + "\n");
            foreach (OutlookStorage.Attachment attachment in message.Attachments)
            {
                str = attachment.Filename + ": " + attachment.Data.Length + " bytes";
                attachmentNode.Nodes.Add(str);
                txtBox.AppendText(str + "\n");
                // Check for SMIME attachment
                if (attachment.Filename.Equals("smime.p7m"))
                {
                    smimefound = true;
                    txtBox.AppendText("==== PKCS#7 Enveloped data ====\n");
                    parsePKCS7(attachment.Data, attachmentNode);
                }
            }

            str = "Sub Messages: " + message.Messages.Count;
            TreeNode subMessageNode = messageNode.Nodes.Add(str);

            txtBox.AppendText(str + "\n");
            foreach (OutlookStorage.Message subMessage in message.Messages)
            {
                this.loadMessage(subMessage, subMessageNode.Nodes.Add("MSG"));
            }
            if (smimefound)
            {
                statusBar.Text = "S/MIME attachment(s) found!";
            }
            else
            {
                statusBar.Text = "No S/MIME attachment(s) found!";
            }
        }
Пример #19
0
 private bool isOutlookMessage(OutlookStorage.Message message)
 {
     return(!String.IsNullOrEmpty(message.BodyRTF) || !String.IsNullOrEmpty(message.BodyText) || !String.IsNullOrEmpty(message.From) || !String.IsNullOrEmpty(message.Subject) || message.Attachments.Count > 0);
 }
        private void button1_Click(object sender, EventArgs e)
        {
            //Extract the email folder to a path where you can use it
            String folderPath = "C:\\Users\\Joe\\Desktop\\DistributionEmails\\Files";

            Int32 iCountNum = 0;

            //Only open files that are email messages
            foreach (String file in Directory.EnumerateFiles(folderPath, "*.msg"))
            {
                try
                {
                    OutlookStorage.Message outlookMsg = new OutlookStorage.Message(file);

                    //Loop through the messages attachments
                    foreach (OutlookStorage.Attachment attach in outlookMsg.Attachments)
                    {
                        byte[] attachBytes = attach.Data;

                        if (attach.Filename.IndexOf(".pdf") > -1 || attach.Filename.IndexOf(".dwf") > -1)
                        {
                            textBox1.AppendText(iCountNum.ToString() + ". " + file + System.Environment.NewLine);
                            int iPos = file.LastIndexOf("\\") + 1;

                            //The filenames come in a few formats. This is the best we have to information about what's in the email
                            string   filename = file.Substring(iPos, (file.Length - iPos));
                            String[] arrItems = Regex.Split(filename, " - ");

                            //connect to the database
                            String        strConn = "Server=mlawdb.cja22lachoyz.us-west-2.rds.amazonaws.com;Database=MLAW_MS;User Id=sa;Password=!sd2the2power!;";
                            SqlConnection conn    = new SqlConnection(strConn);

                            String strMLAWNumber = "";

                            if (arrItems.Length > 1)
                            {
                                //First item is always the date, strip out the word Transmittal if it's in there
                                String strDate = arrItems[0];
                                strDate = strDate.Replace("Transmittal", "").Trim();
                                DateTime dtTime = DateTime.MinValue;

                                try
                                {
                                    dtTime = Convert.ToDateTime(strDate);
                                }
                                catch (System.Exception ex)
                                {
                                    MessageBox.Show(file + ":::" + strDate);
                                }


                                textBox1.AppendText(dtTime.ToString() + System.Environment.NewLine);

                                for (int i = 1; i < arrItems.Length; i++)
                                {
                                    textBox1.AppendText(arrItems[i].ToString() + System.Environment.NewLine);

                                    if (!isTransmittal(arrItems[i].ToString()))
                                    {
                                        String strThis = arrItems[i].ToString().Trim();
                                        strThis = strThis.Replace(".msg", "");

                                        int iCount = strThis.Count(char.IsLetter);

                                        if (iCount < 2 && strThis.Length > 7)
                                        {
                                            iCountNum += 1;

                                            strThis = strThis.Replace(" ", ".");

                                            strMLAWNumber = strThis;


                                            textBox1.AppendText(iCountNum.ToString() + ". " + strThis + System.Environment.NewLine);
                                        }
                                    }
                                }


                                if (strMLAWNumber == "")
                                {
                                    String strAddress = "";

                                    for (int i = 1; i < arrItems.Length; i++)
                                    {
                                        if (!isTransmittal(arrItems[i].ToString()))
                                        {
                                            String strThis = arrItems[i].ToString().Trim();
                                            strThis = strThis.Replace(".msg", "");

                                            int iCount = strThis.Count(char.IsLetter);
                                            textBox1.AppendText("Address: " + strThis + System.Environment.NewLine);


                                            DataSet ds = new DataSet();

                                            //Try to find our MLAW Number based on the Address and the date delivered
                                            SqlCommand sqlComm = new SqlCommand("Get_MLAW_Number_By_Delivery", conn);
                                            sqlComm.Parameters.AddWithValue("@Address", strThis);
                                            sqlComm.Parameters.AddWithValue("@Date", dtTime);

                                            sqlComm.CommandType = CommandType.StoredProcedure;

                                            SqlDataAdapter da = new SqlDataAdapter();
                                            da.SelectCommand = sqlComm;

                                            da.Fill(ds);

                                            if (ds.Tables[0].Rows.Count > 0 && strMLAWNumber == "")
                                            {
                                                strMLAWNumber = ds.Tables[0].Rows[0]["MLAW_Number"].ToString();
                                            }
                                        }
                                    }

                                    //If we manage to get an MLAW Number then we can do something with our file.
                                    if (strMLAWNumber != "")
                                    {
                                        DataSet dsMLAWNum = new DataSet();

                                        SqlCommand sqlCommMLAWNum = new SqlCommand("Get_Order_By_MLAW_Number", conn);
                                        sqlCommMLAWNum.Parameters.AddWithValue("@MLAW_Number", strMLAWNumber);

                                        sqlCommMLAWNum.CommandType = CommandType.StoredProcedure;

                                        SqlDataAdapter daMLAWNum = new SqlDataAdapter();
                                        daMLAWNum.SelectCommand = sqlCommMLAWNum;

                                        daMLAWNum.Fill(dsMLAWNum);

                                        if (dsMLAWNum.Tables[0].Rows.Count > 0)
                                        {
                                            SqlParameter fileP = new SqlParameter("@file", SqlDbType.VarBinary);
                                            fileP.Value = attachBytes;

                                            SqlParameter sqlOrderId = new SqlParameter("@MLAW_Number", SqlDbType.VarChar);
                                            sqlOrderId.Value = strMLAWNumber;

                                            SqlParameter sqlFileName = new SqlParameter("@File_Name", SqlDbType.VarChar);
                                            String       strFileInDB = attach.Filename;

                                            sqlFileName.Value = strFileInDB;

                                            SqlCommand myCommand = new SqlCommand();
                                            myCommand.Parameters.Add(fileP);
                                            myCommand.Parameters.Add(sqlOrderId);
                                            myCommand.Parameters.Add(sqlFileName);


                                            conn.Open();
                                            myCommand.Connection  = conn;
                                            myCommand.CommandText = "Insert_Order_File_2";
                                            myCommand.CommandType = CommandType.StoredProcedure;
                                            myCommand.ExecuteNonQuery();
                                            conn.Close();
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (outlookMsg != null)
                    {
                        outlookMsg.Dispose();
                    }
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
Пример #21
0
        /// <summary>
        /// Drop event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void OnDrop(object sender, Telerik.Windows.DragDrop.DragEventArgs e)
        {
            // Find RadTreeViewItem
            var item = e.OriginalSource as RadTreeViewItem;

            if (e.OriginalSource != null && e.OriginalSource is DependencyObject)
            {
                var dependencySource = (DependencyObject)e.OriginalSource;
                item = Framework.UI.WPFVisualTreeHelper.FindParent <RadTreeViewItem>(dependencySource);
            }

            var targetDirectory = item?.DataContext as DirectoryViewModel;

            // Save target filestructure before drop action
            if (targetDirectory.StructureViewModel.IsDirty)
            {
                targetDirectory.StructureViewModel.Save();
            }
            //Check if the the folder is a workflow folder and has a workflow assigned
            if (IsWorkflowDirectory(targetDirectory))
            {
                return;
            }
            // File drag & drop
            DataObject dataObject           = (e.Data as DataObject);
            var        refreshDirectoryPath = true;

            if (dataObject != null && dataObject.ContainsFileDropList())
            {
                foreach (var file in dataObject.GetFileDropList())
                {
                    Helper.ArchiveHelper.ArchiveFile(targetDirectory.StructureViewModel.Model, targetDirectory.Model, file);
                }

                refreshDirectoryPath = false;
            }
            else if (dataObject != null && dataObject.GetData("FileGroupDescriptorW") != null)
            {
                var outlookDataObject = new OutlookDataObject(dataObject);

                string[] filenames   = (string[])outlookDataObject.GetData("FileGroupDescriptorW");
                var      fileStreams = (MemoryStream[])outlookDataObject.GetData("FileContents");

                string directory = GlobalSettings.AppDataPath + "\\Temp\\Blobs\\";
                if (!System.IO.Directory.Exists(directory))
                {
                    System.IO.Directory.CreateDirectory(directory);
                }

                for (int fileIndex = 0; fileIndex < filenames.Length; fileIndex++)
                {
                    //use the fileindex to get the name and data stream
                    string       filename   = filenames[fileIndex];
                    MemoryStream filestream = fileStreams[fileIndex];

                    //save the file stream using its name to the application path
                    FileStream outputStream = File.Create(directory + filename);
                    filestream.WriteTo(outputStream);
                    outputStream.Close();

                    if (filename.ToLower().EndsWith(".msg"))
                    {
                        try
                        {
                            OutlookStorage.Message msg = new OutlookStorage.Message(directory + filename);
                            DateTime receiveDateTime   = msg.ReceivedDate;
                            msg.Dispose();

                            File.SetLastWriteTime(directory + filename, receiveDateTime);
                        }
                        catch (Exception ex)
                        {
                            Log.LogManagerInstance.Instance.Error(string.Format(@"Invalid mail format: {0}", filename), ex);
                        }
                    }
                    else
                    {
                        File.SetLastWriteTime(directory + filename, DateTime.Now);
                    }

                    Helper.ArchiveHelper.ArchiveFile(targetDirectory.StructureViewModel.Model, targetDirectory.Model, directory + filename);
                }

                refreshDirectoryPath = false;
            }
            else if (dataObject != null && dataObject.GetData(typeof(GridViewPayload)) != null)
            {
                var service             = CommonServiceLocator.ServiceLocator.Current.GetInstance <IFileStructureDocumentPathService>();
                var localizationService = CommonServiceLocator.ServiceLocator.Current.GetInstance <ILocalizationService>();
                var payload             = dataObject.GetData(typeof(GridViewPayload)) as GridViewPayload;

                foreach (var path in payload.DataObjects.OfType <FileStructureDocumenPath>())
                {
                    var copyMode = Keyboard.Modifiers == ModifierKeys.Shift;

                    if (copyMode)
                    {
                        var newPath = new FileStructureDocumenPath
                        {
                            DirectoryGuid     = targetDirectory.Model.Id,
                            FileStructureGuid = targetDirectory.StructureViewModel.Model.Id,
                            DocumentGuid      = path.DocumentGuid,
                            WorkflowId        = targetDirectory.Model.WorkflowId
                        };

                        service.Save(newPath);
                    }
                    else
                    {
                        if (path.IsProtectedPath)
                        {
                            MessageBox.Show(localizationService.Translate("filestructure_path_protected"), localizationService.Translate("filestructure_path_protected_title"), MessageBoxButton.OK, MessageBoxImage.Information);
                            continue;
                        }

                        path.DirectoryGuid     = targetDirectory.Model.Id;
                        path.WorkflowId        = targetDirectory.Model.WorkflowId;
                        path.FileStructureGuid = targetDirectory.StructureViewModel.Model.Id;

                        service.Save(path);
                    }

                    if (targetDirectory.Model.WorkflowId != null)
                    {
                        var configurationService = CommonServiceLocator.ServiceLocator.Current.GetInstance <Workflow.IDocumentWorkflowConfigurationService>();
                        var workflow             = configurationService.Get(targetDirectory.Model.WorkflowId.Value);
                        if (!string.IsNullOrWhiteSpace(workflow.AccessProviderName))
                        {
                            var accessProvider = CommonServiceLocator.ServiceLocator.Current.GetInstance <Workflow.IDocumentWorkflowAccessProvider>(workflow.AccessProviderName);
                            accessProvider.SetUserAccess(GlobalSettings.UserId, path.DocumentGuid, path.Id, path.FileStructureGuid, workflow);
                        }
                    }
                }

                refreshDirectoryPath = false;

                // Refresh grid
                if (payload.Grid is CursorGridViewControl)
                {
                    (payload.Grid as CursorGridViewControl).RefreshData();
                }
            }

            // Save target filestructure before drop action
            if (refreshDirectoryPath)
            {
                targetDirectory.StructureViewModel.Save();
                var directoriesToCheck = new List <DirectoryViewModel>();
                directoriesToCheck.Add(targetDirectory);
                //Recalculating the path through the save method
                while (directoriesToCheck.Any())
                {
                    var innerDirectories = new List <DirectoryViewModel>();

                    foreach (var subDirectory in directoriesToCheck)
                    {
                        var guid = subDirectory.Model.Id;
                        var list = fileStructureDocumentPathService.GetByDirectoryId(guid);
                        foreach (FileStructureDocumenPath fileStructureDocumenPath in list)
                        {
                            fileStructureDocumentPathService.Save(fileStructureDocumenPath);
                        }

                        innerDirectories.AddRange(subDirectory.Directories);
                    }

                    directoriesToCheck.Clear();
                    directoriesToCheck.AddRange(innerDirectories);
                }
            }
        }
Пример #22
0
        // Each message is opened and a tabpage is created dynamically with a header and body box
        private void load_files(string msgfile, string holder, ref int TabCount, string ruleTxt = "", bool fromNode = false)
        {
            bool rulesFileHere = check_for_rules();

            myTab      = new TabPage(holder);
            myTab.Text = holder;
            TextBox HeaderBox = new TextBox();

            HeaderBox.Multiline        = true;
            HeaderBox.Width            = 550;
            HeaderBox.Height           = 960;
            HeaderBox.Location         = new Point(650, 0);
            HeaderBox.ScrollBars       = ScrollBars.Both;
            HeaderBox.ReadOnly         = true;
            HeaderBox.BackColor        = Color.White;
            HeaderBox.WordWrap         = false;
            headerSizeDec.Enabled      = true;
            headerSizeInc.Enabled      = true;
            HeaderBox.ContextMenuStrip = headerMenu;
            myTab.Controls.Add(HeaderBox);

            TextBox BodyBox = new TextBox();

            BodyBox.Multiline        = true;
            BodyBox.Width            = 650;
            BodyBox.Height           = 960;
            BodyBox.ScrollBars       = ScrollBars.Both;
            BodyBox.ReadOnly         = true;
            BodyBox.BackColor        = Color.White;
            BodyBox.WordWrap         = false;
            bodySizeDec.Enabled      = true;
            bodySizeInc.Enabled      = true;
            BodyBox.ContextMenuStrip = bodyMenu;
            myTab.Controls.Add(BodyBox);

            Regex regex_txt = new Regex(@"\.txt$");
            Regex regex_msg = new Regex(@"\.msg$");
            Regex regex_eml = new Regex(@"\.eml$");
            Match match_txt = regex_txt.Match(msgfile);
            Match match_msg = regex_msg.Match(msgfile);
            Match match_eml = regex_eml.Match(msgfile);

            TabCount = TabCount + 1;

            // What type of file are we trying to open.
            if (match_msg.Success)
            {
                Stream messageStream;
                try { messageStream = File.Open(msgfile, FileMode.Open, FileAccess.Read); }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "File Error", MessageBoxButtons.OK);
                    return;
                }
                OutlookStorage.Message message = new OutlookStorage.Message(messageStream);
                messageStream.Close();


                HeaderBox.Text = message.GetMapiPropertyString("007D");
                BodyBox.Text   = message.BodyText;
                message.Dispose();
            }
            else if (match_eml.Success || match_txt.Success)
            {
                StreamReader mStream;
                try { mStream = new StreamReader(msgfile); }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "File Error", MessageBoxButtons.OK);
                    return;
                }

                bool   reachedBody = false;
                bool   firstLine   = true;
                string header      = "";
                string body        = "";

                while (mStream.Peek() >= 0)
                {
                    string lineTest = mStream.ReadLine();
                    if (lineTest != "" && reachedBody == false)
                    {
                        if (!firstLine)
                        {
                            header = header + "\r\n" + lineTest;
                        }
                        else
                        {
                            header = lineTest; firstLine = false;
                        }
                        reachedBody = false;
                    }

                    else if (lineTest == "" && reachedBody == false)
                    {
                        reachedBody    = true;
                        firstLine      = true;
                        HeaderBox.Text = header;
                    }
                    if (reachedBody)
                    {
                        if (!firstLine)
                        {
                            body = body + "\r\n" + lineTest;
                        }
                        else
                        {
                            body = lineTest; firstLine = false;
                        }
                    }
                }
                BodyBox.Text = body;
            }

            // Add a new node to the tree view for these files
            messageNodeInfo nodeNew = new messageNodeInfo();

            nodeNew.headerText             = HeaderBox.Text;
            nodeNew.bodyText               = BodyBox.Text;
            nodeNew.tNode.Text             = holder;
            nodeNew.tNode.Name             = msgfile;
            nodeNew.filePath               = msgfile;
            nodeNew.fileName               = holder;
            nodeNew.tNode.ContextMenuStrip = contextMenuStrip2;
            nodeList.Add(nodeNew);

            tabControl1.TabPages.Add(myTab);
            //tabControl1.Hide();
            closeBtn.Enabled    = true;
            button1.Enabled     = true;
            closeAllBtn.Enabled = true;

            // If a top level treeview node is already selected add the new files to that node
            // Otherwise create a new toplevel node
            if (treeView1.SelectedNode != null)
            {
                if (treeView1.SelectedNode.Level != 0 && fromNode == false)
                {
                    treeView1.SelectedNode.Parent.Nodes.Add(nodeNew.tNode);
                    nodeNew.pNodeIndex = treeView1.SelectedNode.Parent.Index;
                }
                else if (fromNode == false)
                {
                    treeView1.SelectedNode.Nodes.Add(nodeNew.tNode);
                    nodeNew.pNodeIndex = treeView1.SelectedNode.Index;
                }

                treeView1.SelectedNode.Expand();
            }
            else if (treeView1.SelectedNode == null)
            {
                if (treeView1.Nodes.ContainsKey("Untitled") == false)
                {
                    TreeNode newTopNode = new TreeNode("Untitled");
                    newTopNode.Name             = "Untitled";
                    newTopNode.ContextMenuStrip = contextMenuStrip1;
                    nodeNew.pNodeIndex          = treeView1.Nodes.Count;
                    newTopNode.Nodes.Add(nodeNew.tNode);
                    treeView1.Nodes.Add(newTopNode);
                    treeView1.SelectedNode = treeView1.Nodes[newTopNode.Name];
                }
                else
                {
                    ;
                }
            }
            else
            {
                ;
            }
        }
Пример #23
0
        private void loadMessage(OutlookStorage.Message message, TreeNode messageNode)
        {
            String str;

            str = "Outlook Envelope data";
            messageNode.Text = str;
            txtBox.AppendText(str + "\n");

            str = "SMTP Routing Header\n " + message.GetMapiProperty("007D").ToString();
            messageNode.Text = str;
            txtBox.AppendText(str + "\n");

            str = message.Subject;
            messageNode.Nodes.Add(str);
            txtBox.AppendText(str + "\n");

            str = "Subject: " + message.Subject;
            messageNode.Nodes.Add(str);
            txtBox.AppendText(str + "\n");


            /*TreeNode bodyNode = messageNode.Nodes.Add("Body: (double click to view)");
             * bodyNode.Tag = new string[] { message.BodyText, message.BodyRTF };
             */
            str = "Recipients: " + message.Recipients.Count;
            TreeNode recipientNode = messageNode.Nodes.Add(str);

            txtBox.AppendText(str + "\n");
            HashSet <string> targets = new HashSet <string>();

            foreach (OutlookStorage.Recipient recipient in message.Recipients)
            {
                // Load SMIME certificates from AD
                targets.Add(recipient.Email);
                str = recipient.Type + ": " + recipient.Email;
                recipientNode.Nodes.Add(str);
                txtBox.AppendText(str + "\n");
            }

            // Parse out from
            targets.Add(message.GetMapiProperty("5D01").ToString()); // PidTagSenderEmailAddress

            // Old style

            /*
             * string[] strings = Regex.Split(message.GetMapiProperty("007D").ToString(), Environment.NewLine); // PidTagTransportMessageHeaders, https://interoperability.blob.core.windows.net/files/MS-OXPROPS/%5bMS-OXPROPS%5d.pdf
             *
             * foreach (string s in strings)
             * {
             *  if (s.StartsWith("From:"))
             *  {
             *      Match m = Regex.Match(s, "<(.*)>");
             *
             *      if (m.Success)
             *      {
             *          targets.Add(m.Groups[1].Value);
             *      }
             *  }
             * }
             */

            foreach (string target in targets)
            {
                if (!certs.ContainsKey(target))
                {
                    X509Certificate2 cert = GetUserCertificateFromAD(target);
                    if (cert != null)
                    {
                        certs.Add(target, cert);
                    }
                }
            }

            str = "Attachments: " + message.Attachments.Count;
            TreeNode attachmentNode = messageNode.Nodes.Add(str);

            txtBox.AppendText(str + "\n");
            foreach (OutlookStorage.Attachment attachment in message.Attachments)
            {
                str = attachment.Filename + ": " + attachment.Data.Length + " bytes";
                attachmentNode.Nodes.Add(str);
                txtBox.AppendText(str + "\n");
                // Check for SMIME attachment
                if (attachment.Filename.Contains("p7m"))
                {
                    smimefound = true;
                    txtBox.AppendText("==== PKCS#7 Enveloped data ====\n");

                    parsePKCS7(attachment.Data, attachmentNode);
                }
            }

            str = "Sub Messages: " + message.Messages.Count;
            TreeNode subMessageNode = messageNode.Nodes.Add(str);

            txtBox.AppendText(str + "\n");
            foreach (OutlookStorage.Message subMessage in message.Messages)
            {
                this.loadMessage(subMessage, subMessageNode.Nodes.Add("MSG"));
            }
            if (smimefound)
            {
                statusBar.Text = "S/MIME attachment(s) found!";
            }
            else
            {
                statusBar.Text = "No S/MIME attachment(s) found!";
            }
        }
Пример #24
0
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                OutlookStorage.Message msg = messages[listBox1.SelectedIndex];

                lbl_emetteur.Text = "De : " + msg.From;
                lbl_objet.Text    = "Objet : " + msg.Subject;
                txt_corps.Text    = msg.BodyText;

                string rec = "";

                foreach (OutlookStorage.Recipient rcp in msg.Recipients)
                {
                    rec += rcp.Email + " ; ";
                }

                listPJ.Items.Clear();

                foreach (OutlookStorage.Attachment att in msg.Attachments)
                {
                    string extension  = att.Filename.Substring(att.Filename.IndexOf('.'));
                    int    imageIndex = 0;
                    switch (extension)
                    {
                    case ".doc":
                        imageIndex = 16;
                        break;

                    case ".docx":
                        imageIndex = 16;
                        break;

                    case ".xlsx":
                        imageIndex = 15;
                        break;

                    case ".xls":
                        imageIndex = 15;
                        break;

                    case ".csv":
                        imageIndex = 15;
                        break;

                    case ".ppt":
                        imageIndex = 28;
                        break;

                    case ".pptx":
                        imageIndex = 28;
                        break;

                    case ".pdf":
                        imageIndex = 11;
                        break;

                    default:
                        imageIndex = 12;
                        break;
                    }
                    listPJ.Items.Add(att.Filename, imageIndex);
                }

                msgEnCours = msg;


                rec = rec.Remove(rec.Length - 3);
                lbl_destinataire.Text = rec;
            }
            catch (Exception ex)
            {
            }
        }