Пример #1
0
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            string pstFilePath = "sample.pst";

            Outlook.Application app       = new Application();
            NameSpace           outlookNs = app.GetNamespace("MAPI");

            // Add PST file (Outlook Data File) to Default Profile
            outlookNs.AddStore(pstFilePath);
            MAPIFolder rootFolder = outlookNs.Stores["sample"].GetRootFolder();
            // Traverse through all folders in the PST file
            // TODO: This is not recursive
            Folders subFolders = rootFolder.Folders;

            foreach (Folder folder in subFolders)
            {
                Items items = folder.Items;
                foreach (object item in items)
                {
                    if (item is MailItem)
                    {
                        // Retrieve the Object into MailItem
                        MailItem mailItem = item as MailItem;
                        Console.WriteLine("Saving message {0} ....", mailItem.Subject);
                        // Save the message to disk in MSG format
                        // TODO: File name may contain invalid characters [\ / : * ? " < > |]
                        mailItem.SaveAs(@"\extracted\" + mailItem.Subject + ".msg", OlSaveAsType.olMSG);
                    }
                }
            }
            // Remove PST file from Default Profile
            outlookNs.RemoveStore(rootFolder);
        }
Пример #2
0
        public static bool HasLargeAttachments(MailItem mailItem)
        {
            using (var lcfm = new LocalCopyOfFileManager())
            {
                var tempfile = lcfm.GetLocalCopyOfFileTarget(Guid.NewGuid().ToString());
                mailItem.SaveAs(tempfile);

                foreach (Attachment attachment in mailItem.Attachments)
                {
                    try
                    {
                        var file = lcfm.GetLocalCopyOfFileTarget(attachment.FileName);
                        attachment.SaveAsFile(file);
                        var lah = new LargeAttachmentHelper(file);
                        if (lah.IsLargeAttachment)
                        {
                            return true;
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.LogError(e);
                    }
                }
                return false;
            }
        }
Пример #3
0
        public static void SendOne()
        {
            // Create an Outlook Application object.
            Application outLookApp = new Application();
            // Create a new TaskItem.
            MailItem newMail =
                (MailItem)outLookApp.CreateItem(OlItemType.olMailItem);

            // Configure the task at hand and save it.
            newMail.Body       = "Don't forget to send DOM the links...";
            newMail.Importance = OlImportance.olImportanceHigh;
            newMail.Subject    = "Get DOM to stop bugging me.";
            newMail.Recipients.Add("emailaddress");


            var curpwd = pwd();

            newMail.Attachments.Add(curpwd + "myattachment.txt");

            newMail.SaveAs("billburr.msg");



            Console.WriteLine(curpwd);
            Console.ReadKey();
        }
Пример #4
0
        protected override void Execute(CodeActivityContext context)
        {
            Application outlook        = new Application();
            NameSpace   mapi           = outlook.GetNamespace("MAPI");
            MailItem    mail           = mapi.GetItemFromID(MailMessage.Get(context).Headers.Get("UID"));
            string      filePathString = FilePath.Get(context);

            if (Directory.Exists(filePathString))
            {
                string fileName = mail.ReceivedTime.ToString("ddMMyyyy HHmmss") + " " + makeStringFilePathSafe(mail.Subject) + ".msg";
                filePathString = Path.Combine(filePathString, fileName);
            }
            else
            {
                if (!Path.GetFileName(filePathString).EndsWith(".msg"))
                {
                    filePathString += ".msg";
                }
            }
            if (File.Exists(filePathString) && Overwrite)
            {
                File.Delete(filePathString);
            }
            if (!File.Exists(filePathString))
            {
                mail.SaveAs(filePathString);
            }

            ReleaseComObject(mail);
            ReleaseComObject(mapi);
            ReleaseComObject(outlook);
        }
        private void WriteOutputFiles(MailItem mailItem, string destPath)
        {
            var outputFileName = $"{mailItem.SenderEmailAddress} - {mailItem.Subject}.msg";

            // Save the message to disk in MSG format
            // File name may contain invalid characters [\ / : * ? " < > |]
            foreach (char invalidChar in System.IO.Path.GetInvalidFileNameChars())
            {
                outputFileName = outputFileName.Replace(invalidChar, '_');
            }

            Directory.CreateDirectory(destPath);
            string destinationFilenameMsg = destPath + outputFileName;
            string destinationFilenameTxt = destinationFilenameMsg + ".txt";
            string destinationFilenamePdf = destinationFilenameMsg + ".pdf";

            mailItem.SaveAs(destinationFilenameMsg, OlSaveAsType.olMSG);

            if (_outlookMsgParser.Parse(destinationFilenameMsg))
            {
                IParsedContent parsedContent = _outlookMsgParser.ParsedContent.Single <IParsedContent>();

                File.WriteAllText(destinationFilenameTxt, parsedContent.ContentAsString);
                _converter.ConvertFromCom(destinationFilenameTxt, destinationFilenamePdf);

                if (!_keepIntermediateFiles)
                {
                    File.Delete(destinationFilenameTxt);
                    File.Delete(destinationFilenameMsg);
                }
            }
        }
Пример #6
0
        /// <summary>
        /// Converts the Mail file to HTML
        /// </summary>
        /// <param name="filePath">Path to the mail file</param>
        /// <param name="destinationPath">Directory where the HTML file will be saved</param>
        /// <returns>Name of the converted file</returns>
        public string Convert(string filePath, string destinationPath)
        {
            Process     process    = new Process();
            Application appOutlook = null;
            MailItem    mailItem   = null;

            try
            {
                if (Path.GetExtension(filePath) == "." + SupportedExtensions.eml.ToString())
                {
                    foreach (var oldProcess in Process.GetProcessesByName("OUTLOOK"))
                    {
                        oldProcess.Kill();
                    }

                    process.StartInfo.FileName = filePath;
                    process.Start();

                    bool outlookOpen = false;
                    while (!outlookOpen)
                    {
                        try
                        {
                            appOutlook  = (Application)Marshal.GetActiveObject("Outlook.Application");
                            outlookOpen = true;
                        }
                        catch
                        {
                            Thread.Sleep(100);
                        }
                    }
                    mailItem = (MailItem)appOutlook.ActiveInspector().CurrentItem;
                }
                else
                {
                    appOutlook = new Application();
                    mailItem   = (MailItem)appOutlook.Session.OpenSharedItem(filePath);
                }
                string fileName = Path.GetFileNameWithoutExtension(filePath) + DateTime.Now.Ticks + ".html";

                if (!Directory.Exists(destinationPath))
                {
                    Directory.CreateDirectory(destinationPath);
                }
                mailItem.SaveAs(Path.Combine(destinationPath, fileName), OlSaveAsType.olHTML);

                return(fileName);
            }
            catch
            {
                return(null);
            }
            finally
            {
                mailItem?.Close(OlInspectorClose.olDiscard);
                appOutlook?.Quit();
                process.Dispose();
            }
        }
Пример #7
0
        public void Save_item(List <string> mappen, MailItem Item, string clientnr, string mail, List <string> mappen2)
        {
            string map_doel = "";
            string Item_naam;
            int    year  = Item.SentOn.Year;
            int    month = Item.SentOn.Month;
            int    day   = Item.SentOn.Day;

            string date = year + "-" + month + "-" + day + " " + Item.SentOn.Hour + " " + Item.SentOn.Minute + " " + Item.SentOn.Second;

            string sPathFile = @"D:\Data\Corespondentie map automatische mail\" + clientnr + @"\" + year + @"\";

            CreateDir(sPathFile);

            foreach (string element in mappen)
            {
                if (element.EndsWith(clientnr + @"\Correspondentie"))
                {
                    CreateDir(element + @"\" + year);
                    map_doel = element + @"\" + year;

                    UrlShortcut(clientnr, year, map_doel);
                }
                if (element.Contains(clientnr + @"\Correspondentie\" + year))
                {
                    map_doel = element;

                    UrlShortcut(clientnr, year, map_doel);
                }
            }
            map_doel  = sPathFile;
            Item_naam = Item.Subject;
            Item_naam = RemoveIllegalFileNameChars(Item_naam);
            if (Item_naam.Length > 100)
            {
                Item_naam = Item_naam.Substring(0, 100);
            }
            if (clientnr == "99999999999999999999999999")
            {
                Item_naam = "mail adress" + " " + RemoveIllegalFileNameChars(mail);
                if (Item_naam.Length > 100)
                {
                    Item_naam = Item_naam.Substring(0, 100);
                }
                date            = "";
                Item.Categories = "Onbekend mail adress";
            }
            else
            {
                Item.Categories = "Automatisch gearchiveerd";
            }

            if (!System.IO.File.Exists(map_doel + PATHSEPARATOR + date + " " + Item_naam + MAIL_SAVEFILE_EXT))
            {
                Item.SaveAs(map_doel + PATHSEPARATOR + date + " " + Item_naam + MAIL_SAVEFILE_EXT, MAIL_SAVETYPE);
            }
            Item.Save();
        }
        private void CreateRegisteredEmail(MailItem mailitem)
        {
            Application outlookApp    = new Application();
            MailItem    encryptedMail = outlookApp.CreateItem(OlItemType.olMailItem) as MailItem;

            encryptedMail.To         = mailitem.To;
            encryptedMail.CC         = mailitem.CC;
            encryptedMail.BCC        = mailitem.BCC;
            encryptedMail.Subject    = mailitem.Subject;
            encryptedMail.BodyFormat = mailitem.BodyFormat;
            encryptedMail.Body       = mailitem.Body;
            encryptedMail.HTMLBody   = mailitem.HTMLBody;
            encryptedMail.Importance = mailitem.Importance;

            try
            {
                if (mailitem.Attachments.Count > 0)
                {
                    for (int x = 1; x <= mailitem.Attachments.Count; x++)
                    {
                        mailitem.Attachments[x].SaveAsFile(fileHelper.FilePathGenerator(mailitem.Attachments[x].FileName));
                        encryptedMail.Attachments.Add(fileHelper.FilePathGenerator(mailitem.Attachments[x].FileName), OlAttachmentType.olByValue, 1, mailitem.Attachments[x].FileName);
                        File.Delete(fileHelper.FilePathGenerator(mailitem.Attachments[x].FileName));
                    }
                }
            }
            catch (System.Exception ex)
            {
                // System.Windows.Forms.MessageBox.Show(ex.Message+"\r\n"+ex.InnerException);
            }

            //Remove attachments from email
            int originalAttachmentsCount = mailitem.Attachments.Count;

            for (int x = 1; x <= originalAttachmentsCount; x++)
            {
                mailitem.Attachments.Remove(1);
            }

            // Encrypt email with attachments if any
            string filePath = fileHelper.FilePathGenerator(encryptedMail.Subject) + ".msg";

            encryptedMail.SaveAs(filePath);
            string encryptedFilePath = EncryptSavedEmail(filePath);

            // Add encrypted email as an attachment
            mailitem.Attachments.Add(encryptedFilePath, OlAttachmentType.olByValue, 1, encryptedFilePath);

            //Hash encrypted email
            securityHelper = new SecurityHelper();
            mailitem.Body  = "Email is encrypted and ready to be sent! \n\r" + "Encrypted email hash is " + securityHelper.HashFile(encryptedFilePath) + "\n\r" + "Your Email ID is " + EmailId;

            //Delete encrypted email
            File.Delete(filePath);
        }
Пример #9
0
        private string convertMsg(Application outlook, string fileName, string htmlFile, string outDir)
        {
            MailItem mailItem = (MailItem)outlook.CreateItemFromTemplate(fileName);

            mailItem.SaveAs(htmlFile, OlSaveAsType.olHTML);

            HtmlDocHandler htmlDocHandler = (HtmlDocHandler)docHandlerFactory.GetDocHandler(DocConstants.DOC_HANDLER_HTML);

            if (htmlDocHandler == null)
            {
                throw new System.Exception("HTML Doc Handler not found.");
            }
            return(htmlDocHandler.ConvertToPDF(htmlFile, outDir));
        }
Пример #10
0
        private void OpenMsgInOutlook()
        {
            var appdataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "StatusMaker");

            if (!Directory.Exists(appdataFolder))
            {
                Directory.CreateDirectory(appdataFolder);
            }

            var statusMsgFilePath = Path.Combine(appdataFolder, Guid.NewGuid().ToString() + ".msg");

            outlookMsg.SaveAs(statusMsgFilePath);
            Process.Start(statusMsgFilePath);
        }
Пример #11
0
 private void StyleButton_Click(object sender, EventArgs e)
 {
     CreateBodyMail();
     if (questionList.Items.Count == 0)
     {
         warningLabelEmpty.Text = "You can't create template with no questions";
     }
     else
     {
         //check if directory exist
         if (!Directory.Exists(Configuration.pathFileTemplate))
         {
             Directory.CreateDirectory(Configuration.pathFileTemplate);
         }
         if (czyEdytujemy == false)
         {
             if (textBox2.Text.Equals(""))
             {
                 warningLabelName.Text = "Please enter a name";
             }
             else
             {
                 if (File.Exists(Configuration.pathFileTemplate + "\\" + textBox2.Text + ".oft"))
                 {
                     warningLabelName.Text = "This file exists. We cannot save";
                 }
                 else
                 {
                     Application outlookApp = new Application();
                     MailItem    mailItem   = outlookApp.CreateItem(OlItemType.olMailItem);
                     mailItem.HTMLBody = CreateBodyMail();
                     mailItem.SaveAs(Configuration.pathFileTemplate + "\\" + textBox2.Text + ".oft");
                     mailItem.Display();
                     Close();
                 }
             }
         }
         else
         {
             MessageBox.Show("RZECZYWISCIE ZAPISUJEMY EDYTOWANY PLIK");
             Outlook.Application outlookApp = new Outlook.Application();
             MailItem            mailItem   = outlookApp.CreateItem(OlItemType.olMailItem);
             mailItem.HTMLBody = CreateBodyMail();
             string nazwaPliku = label1.Text.Substring(17);
             mailItem.SaveAs(Configuration.pathFileTemplate + "\\" + nazwaPliku);
             mailItem.Display();
             Close();
         }
     }
 }
Пример #12
0
 private string ExtractEmailBody(MailItem objMail, string folder, string name)
 {
     try
     {
         string body = objMail.Body;
         string path = Path.Combine(folder, name);
         Directory.CreateDirectory(folder);
         objMail.SaveAs(path, OlSaveAsType.olRTF);
         return(path);
     }
     catch (Exception exception1)
     {
         MessageBox.Show("Sth happened while working on file " + folder + name + ". \n Error caught: " + exception1.Message);
         return("");
     }
 }
Пример #13
0
        public async override Task RunCommand(object sender)
        {
            var      engine  = (IAutomationEngineInstance)sender;
            MailItem message = (MailItem)await v_MailItem.EvaluateCode(engine);

            string msgDirectory = (string)await v_MailItemDirectory.EvaluateCode(engine);

            string msgFileName = (string)await v_MailItemFileName.EvaluateCode(engine);

            if (!Directory.Exists(msgDirectory))
            {
                Directory.CreateDirectory(msgDirectory);
            }

            message.SaveAs(Path.Combine(msgDirectory, msgFileName + ".msg"));
        }
Пример #14
0
        /// <summary>The save email.</summary>
        /// <param name="mailItem">The mailItem.</param>
        /// <returns>The <see cref="string"/> path.</returns>
        private string SaveEmail(MailItem mailItem)
        {
            if (mailItem == null)
            {
                throw new ArgumentNullException("mailItem");
            }

            var validName    = mailItem.Subject;
            var invalidChars = Path.GetInvalidFileNameChars();

            validName = invalidChars.Aggregate(
                validName,
                (current, c) => current.Replace(c.ToString(CultureInfo.InvariantCulture), string.Empty));
            var path = string.Format(CultureInfo.InvariantCulture, "{0}.msg", validName);

            mailItem.SaveAs(path);
            return(path);
        }
        private void ProcessEmail(MailItem mail, string msgDirectory, string attDirectory)
        {
            if (v_MarkAsRead == "Yes")
            {
                mail.UnRead = false;
            }

            if (v_SaveMessagesAndAttachments == "Yes")
            {
                if (Directory.Exists(msgDirectory))
                {
                    if (string.IsNullOrEmpty(mail.Subject))
                    {
                        mail.Subject = "(no subject)";
                    }

                    string mailFileName = string.Join("_", mail.Subject.Split(Path.GetInvalidFileNameChars()));
                    mail.SaveAs(Path.Combine(msgDirectory, mailFileName + Guid.NewGuid() + ".msg"));
                }

                if (Directory.Exists(attDirectory))
                {
                    if (v_IncludeEmbeddedImagesAsAttachments.Equals("Yes"))
                    {
                        foreach (Attachment attachment in mail.Attachments)
                        {
                            attachment.SaveAsFile(Path.Combine(attDirectory, attachment.FileName));
                        }
                    }
                    else
                    {
                        foreach (Attachment attachment in mail.Attachments)
                        {
                            var flags = mail.HTMLBody.Contains(attachment.FileName);

                            if (!flags)
                            {
                                attachment.SaveAsFile(Path.Combine(attDirectory, attachment.FileName));
                            }
                        }
                    }
                }
            }
        }
Пример #16
0
        private void IndexBtn_Click(object sender, EventArgs e)
        {
            string folder   = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\XLant\\temp\\";
            string tempPath = folder + "temp.msg";

            email.SaveAs(tempPath);

            string cabinet   = XLVirtualCabinet.FileStore(client.office, client.department);
            string clientStr = client.clientcode + " - " + client.name;
            string status    = "";

            if (email.ReceivedTime != null)
            {
                status = "External";
            }
            else if (email.SentOn != null)
            {
                status = "Sent";
            }
            else
            {
                status = "Draft";
            }
            XLMain.Staff toBe    = (XLMain.Staff)ToBeActionDDL.SelectedItem;
            string       desc    = DescTB.Text;
            string       section = "";

            if (client.department != "INS")
            {
                section = "Correspondence";
            }
            else
            {
                section = FileSectionDDL.SelectedItem.ToString();
            }
            //Launch the index process and collect the result
            XLVirtualCabinet.BondResult outcome = XLVirtualCabinet.IndexDocument(tempPath, cabinet, clientStr, status, toBe.name, section, desc);

            //close the dialog in any event.
            this.Close();
        }
Пример #17
0
 private void ProcessEmail(MailItem mail, string msgDirectory, string attDirectory)
 {
     if (v_MarkAsRead == "Yes")
     {
         mail.UnRead = false;
     }
     if (v_SaveMessagesAndAttachments == "Yes")
     {
         if (System.IO.Directory.Exists(msgDirectory))
         {
             mail.SaveAs(System.IO.Path.Combine(msgDirectory, mail.Subject + ".msg"));
         }
         if (System.IO.Directory.Exists(attDirectory))
         {
             foreach (Attachment attachment in mail.Attachments)
             {
                 attachment.SaveAsFile(System.IO.Path.Combine(attDirectory, attachment.FileName));
             }
         }
     }
 }
        private void ProcessEmail(MailItem mail, string msgDirectory, string attDirectory)
        {
            if (v_MarkAsRead == "Yes")
            {
                mail.UnRead = false;
            }
            if (v_SaveMessagesAndAttachments == "Yes")
            {
                if (Directory.Exists(msgDirectory))
                {
                    string mailFileName = string.Join("_", mail.Subject.Split(Path.GetInvalidFileNameChars()));
                    mail.SaveAs(Path.Combine(msgDirectory, mailFileName + ".msg"));
                }

                if (Directory.Exists(attDirectory))
                {
                    foreach (Attachment attachment in mail.Attachments)
                    {
                        attachment.SaveAsFile(Path.Combine(attDirectory, attachment.FileName));
                    }
                }
            }
        }
Пример #19
0
        public ReportMail(ModelReportMail repData, string reportType)
        {
            //// Create new E Mail
            MailItem mail = (MailItem)OutlookApp.CreateItem(OlItemType.olMailItem);

            mail.To      = ModelConfiguration.Instance.ReportAddress;
            mail.Subject = repData.Subject;
            mail.Body    = repData.DetailedText;

            // Attach the selected mail and score results if necessary
            if (repData.Scoring != null)
            {
                // Generate XML with detailed infos
                XElement scoreDetails = new XElement("ScoreDetails",
                                                     (from CheckResult in repData.Scoring.DetailedScoreInfo
                                                      select new XElement("Result",
                                                                          new XElement("Score", CheckResult.score),
                                                                          new XElement("Id", CheckResult.id),
                                                                          new XElement("Fragment", CheckResult.fragment),
                                                                          new XElement("Ioc", CheckResult.ioc))
                                                     )
                                                     );
                // Get the problematic mail
                MailItem attMail = (MailItem)OutlookApp.GetNamespace("MAPI").GetItemFromID(repData.Scoring.MailitemEntryID);

                var tmpPath = Path.GetTempPath() + "FinalFrontier\\";

                if (!Directory.Exists(tmpPath))
                {
                    Directory.CreateDirectory(tmpPath);
                }
                tmpPath += Path.GetRandomFileName();
                var tmpPath2 = tmpPath + "1";

                scoreDetails.Save(tmpPath + ".xml");
                attMail.SaveAs(tmpPath2);

                // Generate attachements
                mail.Attachments.Add(tmpPath);
                mail.Attachments.Add(tmpPath2);
            }

            mail.Send();


            switch (reportType)
            {
            case "fp":
                // Later use
                break;

            case "bug":
                // Later use
                break;

            case "feature":
                // Later use
                break;

            default:
                throw new ArgumentException("This type of report is not supportet. Only use 'fp', 'bug' oder'feature'.");
            }
        }
Пример #20
0
        public static void SavePSTFile(IEnumerable <MailItem> pstfile)
        {
            foreach (object item in pstfile)

            {
                if (item is MailItem)
                {
                    // Retrieve the Object into MailItem

                    MailItem mailItem = item as MailItem;

                    Console.WriteLine("Saving message {0} ....", mailItem.Subject);

                    var      sent       = mailItem.SentOn;
                    var      sentDate   = sent.ToString("MMM dd yyyy hh-mmtt");
                    var      bodystring = mailItem.Body;
                    string[] bodyarray  = new string[0];

                    if (bodystring != null)
                    {
                        bodyarray = bodystring.Split(' ');
                    }



                    if (bodyarray != null)
                    {
                        var stringToCheck = "Reference:";
                        var subject       = " ";
                        var fullsubject   = " ";

                        for (int i = 0; i < bodyarray.Length; i++)
                        {
                            string check = bodyarray[i];

                            if (check == stringToCheck)
                            {
                                subject = bodyarray[i + 1];
                            }
                        }



                        var Sent = mailItem.To;


                        var sentFinal = " ";

                        if (Sent != null)
                        {
                            Regex pattern = new Regex("[<>:?|/\"*]");
                            sentFinal = pattern.Replace(Sent, "!");
                        }


                        var newname = sentFinal;

                        var subjectFinal = TS.TruncateLongString(subject, 10);


                        //fullsubject = subjectFinal + " " + sentDate;


                        if (subject != " ")
                        {
                            string filepath = @"I:\Emails20172018\" + subjectFinal + "-" + sentDate + " " + sentFinal + ".msg";

                            if (!File.Exists(filepath))
                            {
                                mailItem.SaveAs(filepath, OlSaveAsType.olMSG);
                            }
                        }

                        else if (mailItem.To != null)
                        {
                            string filepath2 = @"I:\Emails20172018\Unknown Email -" + sentDate + " " + sentFinal + ".msg";

                            if (!File.Exists(filepath2))
                            {
                                mailItem.SaveAs(filepath2, OlSaveAsType.olMSG);
                            }
                        }

                        else
                        {
                            string filepath3 = @"I:\Emails20172018\Unknown Email -" + sentDate + " NoAddress.msg";
                            if (!File.Exists(filepath3))
                            {
                                mailItem.SaveAs(filepath3, OlSaveAsType.olMSG);
                            }
                        }
                    }
                }
            }
        }
Пример #21
0
        public static void SaveMail(OutlookApp outlookApp, List <string> attachedFileList, string subject, List <string> originatorRecipientList, List <string> toTypeRecipients, List <string> ccTypeRecipient, List <string> bccTypeRecipient, string mailBody, string mailHtmlBody, out string err, string path)
        {
            err = string.Empty;
            MailItem mail = outlookApp.OutlookAppInstance.CreateItem(OlItemType.olMailItem) as MailItem;

            mail.Subject = subject;
            mail.Body    = mailBody;
            if (mailHtmlBody != null)
            {
                mail.HTMLBody = mailHtmlBody;
            }
            AddressEntry currentUser = outlookApp.OutlookAppInstance.Session.CurrentUser.AddressEntry;

            if (toTypeRecipients != null && toTypeRecipients.Count > 0)
            {
                foreach (string recipient in toTypeRecipients)
                {
                    if (!string.IsNullOrEmpty(recipient))
                    {
                        Recipient toRecipient = mail.Recipients.Add(recipient);
                        toRecipient.Type = (int)OlMailRecipientType.olTo;
                    }
                }
            }

            if (originatorRecipientList != null && originatorRecipientList.Count > 0)
            {
                foreach (string recipient in originatorRecipientList)
                {
                    Recipient originalRecipient = mail.Recipients.Add(recipient);
                    originalRecipient.Type = (int)OlMailRecipientType.olOriginator;
                }
            }

            if (ccTypeRecipient != null && ccTypeRecipient.Count > 0)
            {
                foreach (string recipient in ccTypeRecipient)
                {
                    if (!string.IsNullOrEmpty(recipient))
                    {
                        Recipient ccRecipient = mail.Recipients.Add(recipient);
                        ccRecipient.Type = (int)OlMailRecipientType.olCC;
                    }
                }
            }

            if (bccTypeRecipient != null && bccTypeRecipient.Count > 0)
            {
                foreach (string recipient in bccTypeRecipient)
                {
                    Recipient bccRecipient = mail.Recipients.Add(recipient);
                    bccRecipient.Type = (int)OlMailRecipientType.olBCC;
                }
            }

            bool isResolveSuccess = mail.Recipients.ResolveAll();

            if (!isResolveSuccess)
            {
                err += "Warning: There's error when resolve the recipients' names";
            }


            if (attachedFileList != null)
            {
                try
                {
                    foreach (string attachedFilePath in attachedFileList)
                    {
                        mail.Attachments.Add(attachedFilePath, OlAttachmentType.olByValue, Type.Missing, Type.Missing);
                    }
                }
                catch (System.Exception ex)
                {
                    err += "Error: There's error when adding attach file to the mail " + ex.Message;
                    Console.WriteLine("There's error when adding attach file to the mail " + ex.Message);
                }
            }
            mail.SaveAs(path, Type.Missing);
        }
        private async Task CopyMove(object item, Folder backupFolder, ExportOptions exportOptions, DirectoryInfo root)
        {
            await Task.Yield();

            if (item is MailItem)
            {
                try
                {
                    MailItem mailItem = (MailItem)item;
                    if (
                        (exportOptions.mailItemFlag == ExportFlag.All) ||
                        (exportOptions.mailItemFlag != ExportFlag.Exclude) ||
                        (exportOptions.mailItemFlag == ExportFlag.Filter && Between(mailItem.CreationTime, exportOptions.exportStart, exportOptions.exportEnd))
                        )
                    {
                        ////copy
                        //MailItem copiedMailItem = mailItem.Copy();
                        //copiedMailItem.Move(backupFolder);
                        //
                        ////audit
                        //Console.WriteLine(backupFolder.FolderPath + "\t MailItem \t" + mailItem.Subject + "\t" + mailItem.ReceivedTime);
                        //
                        //
                        ////close items
                        //mailItem.Close(OlInspectorClose.olDiscard);
                        //copiedMailItem.Close(OlInspectorClose.olDiscard);

                        mailItem.SaveAs(root.FullName + "\\" + mailItem.EntryID + ".msg", OlSaveAsType.olMSGUnicode);
                        mailItem.Close(OlInspectorClose.olDiscard);

                        Marshal.ReleaseComObject(mailItem);  //cannot set to null before this call
                        Marshal.FinalReleaseComObject(mailItem);
                    }
                }
                catch (System.Exception e)
                {
                    Console.WriteLine(e);
                }
            }
            //else if (item is AppointmentItem)
            //{
            //    try
            //    {
            //        AppointmentItem appointmentItem = (AppointmentItem)item;
            //
            //        if ((exportOptions.appointmentItemFlag != ExportFlag.Exclude && Between(appointmentItem.CreationTime, exportOptions.exportStart, exportOptions.exportEnd)) || exportOptions.appointmentItemFlag == ExportFlag.All)
            //        {
            //            //copy
            //            appointmentItem.CopyTo((MAPIFolder)backupFolder, OlAppointmentCopyOptions.olCreateAppointment);
            //
            //            //audit
            //            Console.WriteLine(backupFolder.FolderPath + "\t AppointmentItem \t" + appointmentItem.Subject + "\t" + appointmentItem.StartUTC);
            //
            //            //closeitems
            //            appointmentItem.Close(OlInspectorClose.olDiscard);
            //        }
            //    }
            //    catch (System.Exception e)
            //    {
            //        Console.WriteLine(e);
            //    }
            //}
            //else if (item is ContactItem)
            //{
            //    try
            //    {
            //        ContactItem contactItem = (ContactItem)item;
            //
            //        if ((exportOptions.contactItemFlag != ExportFlag.Exclude && Between(contactItem.CreationTime, exportOptions.exportStart, exportOptions.exportEnd)) || exportOptions.contactItemFlag == ExportFlag.All)
            //        {
            //            //copy
            //            ContactItem copiedContactItem = contactItem.Copy();
            //            copiedContactItem.Move(backupFolder);
            //
            //            //audit
            //            Console.WriteLine("\t ContactItem \t" + copiedContactItem.LastName + ", " + copiedContactItem.FirstName);
            //
            //            //closeitems
            //            contactItem.Close(OlInspectorClose.olDiscard);
            //            copiedContactItem.Close(OlInspectorClose.olDiscard);
            //        }
            //    }
            //    catch (System.Exception e)
            //    {
            //        Console.WriteLine(e);
            //    }
            //}
            //else if (item is MeetingItem)
            //{
            //    try
            //    {
            //        MeetingItem meetingItem = (MeetingItem)item;
            //
            //        if ((exportOptions.meetingItemFlag != ExportFlag.Exclude && Between(meetingItem.CreationTime, exportOptions.exportStart, exportOptions.exportEnd)) || exportOptions.meetingItemFlag == ExportFlag.All)
            //        {
            //            //copy
            //            MeetingItem copiedMeetingItem = meetingItem.Copy();
            //            copiedMeetingItem.Move(backupFolder);
            //
            //            //audit
            //            Console.WriteLine(backupFolder.FolderPath + "\t MeetingItem \t" + copiedMeetingItem.Subject + "\t" + copiedMeetingItem.ReceivedTime);
            //
            //            //closeitems
            //            meetingItem.Close(OlInspectorClose.olDiscard);
            //            copiedMeetingItem.Close(OlInspectorClose.olDiscard);
            //        }
            //    }
            //    catch (System.Exception e)
            //    {
            //        Console.WriteLine(e);
            //    }
            //}
            //else if (item is TaskItem)
            //{
            //    try
            //    {
            //        TaskItem taskItem = (TaskItem)item;
            //
            //        if ((exportOptions.taskItemFlag != ExportFlag.Exclude && Between(taskItem.CreationTime, exportOptions.exportStart, exportOptions.exportEnd)) || exportOptions.taskItemFlag == ExportFlag.All)
            //        {
            //
            //            //copy
            //            TaskItem copiedtaskItem = taskItem.Copy();
            //            copiedtaskItem.Move(backupFolder);
            //
            //            //audit
            //            Console.WriteLine(backupFolder.FolderPath + "\t TaskItem \t" + copiedtaskItem.Subject + "\t" + copiedtaskItem.CreationTime);
            //
            //            //closeitems
            //            taskItem.Close(OlInspectorClose.olDiscard);
            //            copiedtaskItem.Close(OlInspectorClose.olDiscard);
            //        }
            //    }
            //    catch (System.Exception e)
            //    {
            //        Console.WriteLine(e);
            //    }
            //}
            //else if (item is JournalItem)
            //{
            //    try
            //    {
            //        JournalItem journalItem = (JournalItem)item;
            //
            //        if ((exportOptions.journalItemFlag != ExportFlag.Exclude && Between(journalItem.CreationTime, exportOptions.exportStart, exportOptions.exportEnd)) || exportOptions.journalItemFlag == ExportFlag.All)
            //        {
            //            //copy
            //            JournalItem copiedjournalItem = journalItem.Copy();
            //            copiedjournalItem.Move(backupFolder);
            //
            //            //audit
            //            Console.WriteLine(backupFolder.FolderPath + "\t JournalItem \t" + copiedjournalItem.Subject + "\t" + copiedjournalItem.CreationTime);
            //
            //            //closeitems
            //            journalItem.Close(OlInspectorClose.olDiscard);
            //            copiedjournalItem.Close(OlInspectorClose.olDiscard);
            //        }
            //    }
            //    catch (System.Exception e)
            //    {
            //        Console.WriteLine(e);
            //    }
            //}
            //else
            //{
            //    try
            //    {
            //        if (exportOptions.otherItemFlag == ExportFlag.All)
            //        {
            //            Console.WriteLine("Couldn't Identify mail item at " + backupFolder.FolderPath);
            //        }
            //    }
            //    catch (System.Exception e)
            //    {
            //        Console.WriteLine(e);
            //    }
            //}
        }
Пример #23
0
        /// <summary>
        /// Sends the selected emails using the specified profile
        /// </summary>
        /// <param name="profileID"></param>
        public static void SendReports(string profileID)
        {
            SpamGrabberCommon.Profile profile = new SpamGrabberCommon.Profile(profileID);

            if (profile.AskVerify)
            {
                if (MessageBox.Show("Are you sure you want to report the selected item(s)?", "Report messages", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    return;
                }
            }

            Explorer exp = _app.Application.ActiveExplorer();

            // Create a collection to hold references to the attachments
            List <string> attachmentFiles = new List <string>();

            // Make sure at least one item is sent
            bool bItemsSelected = false;

            // First make sure the selected emails have been downloaded
            bool bNeedsSendReceive = false;

            for (int i = 1; i <= exp.Selection.Count; i++)
            {
                if (exp.Selection[i] is MailItem)
                {
                    MailItem mail = (MailItem)exp.Selection[i];
                    bItemsSelected = true;
                    // If the item has not been downloaded, mark for download
                    if (mail.DownloadState == OlDownloadState.olHeaderOnly)
                    {
                        bNeedsSendReceive    = true;
                        mail.MarkForDownload = OlRemoteStatus.olMarkedForDownload;
                        mail.Save();
                    }
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(mail);
                }
            }
            if (bNeedsSendReceive)
            {
                // Download the marked emails
                // TODO: Trying to carry on at this point returns blank email bodies. Try and find a way of downloading them properly.
                _app.Session.SendAndReceive(false);
                MessageBox.Show("One of more emails were not downloaded from the server. Please ensure they are now downloaded and click report again",
                                "SpamGrabber", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            if (bItemsSelected)
            {
                // Now get references to all the items
                for (int i = 1; i <= exp.Selection.Count; i++)
                {
                    if (exp.Selection[i] is MailItem)
                    {
                        MailItem mail = (MailItem)exp.Selection[i];
                        if (profile.UseRFC)
                        {
                            // Direct attaching seems to be buggy. Save the mailitem first
                            string fileName = Path.Combine(Path.GetTempPath(), Path.GetTempFileName() + ".msg");
                            mail.SaveAs(fileName);
                            attachmentFiles.Add(fileName);
                        }
                        else
                        {
                            // Create temp text file
                            string     fileName = Path.Combine(Path.GetTempPath(), Path.GetTempFileName() + ".txt");
                            TextWriter tw       = new StreamWriter(fileName);
                            tw.Write(GetMessageSource(mail, profile.CleanHeaders));
                            tw.Close();
                            attachmentFiles.Add(fileName);
                        }
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(mail);
                    }
                }

                // Are we using a single email or one per report?
                if (profile.SendMultiple)
                {
                    // Create the report email
                    MailItem reportEmail = CreateReportEmail(profile);

                    // Attach the files
                    foreach (string attachment in attachmentFiles)
                    {
                        reportEmail.Attachments.Add(attachment);
                    }

                    // Do we need to keep a copy?
                    if (!profile.KeepCopy)
                    {
                        reportEmail.DeleteAfterSubmit = true;
                    }
                    // Send the report
                    reportEmail.Send();

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(reportEmail);
                }
                else
                {
                    // Send one email per report
                    foreach (string attachment in attachmentFiles)
                    {
                        MailItem reportEmail = CreateReportEmail(profile);
                        reportEmail.Attachments.Add(attachment);
                        // Do we need to keep a copy?
                        if (!profile.KeepCopy)
                        {
                            reportEmail.DeleteAfterSubmit = true;
                        }
                        reportEmail.Send();
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(reportEmail);
                    }
                }

                // Sort out actions on the source emails
                for (int i = 1; i <= exp.Selection.Count; i++)
                {
                    if (exp.Selection[i] is MailItem)
                    {
                        MailItem mail = (MailItem)exp.Selection[i];
                        if (profile.MarkAsReadAfterReport)
                        {
                            mail.UnRead = false;
                        }
                        if (profile.MoveToFolderAfterReport)
                        {
                            mail.Move(_app.GetNamespace("MAPI").GetFolderFromID(
                                          profile.MoveFolderName, profile.MoveFolderStoreId));
                        }
                        if (profile.DeleteAfterReport)
                        {
                            mail.UnRead = false;
                            mail.Delete();
                        }
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(mail);
                    }
                }
            }
        }