Example #1
0
        private void ProcessMessage(MailItem mailItem)
        {
            bool isAwsNotification =
                mailItem.SenderEmailAddress == AWSNotification.EMAIL_ADDRESS &&
                mailItem.Body != null;

            string newSubject = mailItem.Subject;

            if (isAwsNotification)
            {
                if (mailItem.Body.StartsWith(CodeCommit.PULL_REQUEST_BODY_PREFIX))
                {
                    newSubject = GetNewPullRequestSubject(mailItem.Body);
                }
                else if (mailItem.Body.StartsWith(CodePipeline.BODY_PREFIX))
                {
                    newSubject = GetNewCodePipelineSubject(mailItem.Body);
                }
                else if (mailItem.Body.StartsWith(CodeCommit.CODE_COMPARE_COMMENT_BODY_PREFIX))
                {
                    newSubject = GetNewCodeCompareSubject(mailItem.Body);
                }

                if (newSubject != mailItem.Subject)
                {
                    mailItem.Subject = newSubject;
                    mailItem.Save();
                }
            }
        }
Example #2
0
        private void setDocumentType(MailItem objMail, string itemType, string country, bool isSent)
        {
            //handle deleted emails
            try
            {
                this.setEmailType(objMail, country);
                if (isSent || (objMail == null))
                {
                    objMail.UserProperties["Document Type"].Value = itemType;
                }
                else
                {
                    itemType = "NOT DELIVERED";
                    objMail.UserProperties["Document Type"].Value = itemType;
                }

                objMail.Save();
            }
            catch (Exception e)
            {
                String       caption = "OOPS";
                String       message = "Snap! \n\nWhy have you deleted the email right after sending it to EDMS? \nPlease check it in Easy. If something got lost - recover email. Re-send. Check Easy.\n\nAnd here goes error call stack (share it with SD):\n\n" + e.StackTrace;
                DialogResult result;
                result = MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Hand);
            }
        }
        public static MailItem AddMailItem()
        {
            MailItem mailItem = (MailItem)GetApplication().CreateItem(OlItemType.olMailItem);

            mailItem.Save();
            return(mailItem);
        }
        public void SendMail(MailItem mailItem)
        {
            if (mailItem.FlagRequest == MailServiceSettings.CopyMailFlag)
            {
                MAPIFolder folder = _Application.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail);
                mailItem.Move(folder);
                return;
            }
            if (mailItem.FlagRequest != MailServiceSettings.AutoMailFlag)
            {
                string to = $"{mailItem.To}; {mailItem.CC}";

                Outlook.Folder selectedFolder = StartDialogService();
                if (selectedFolder != null)
                {
                    mailItem.SaveSentMessageFolder = selectedFolder;
                    mailItem.Save();
                    MailItem copyMail = mailItem.Copy();
                    copyMail.FlagRequest = MailServiceSettings.CopyMailFlag;
                    copyMail.Save();
                    SendToRecipients(to);
                }
            }
            mailItem.Send();
        }
        public static void RemoveUserProperty(MailItem mailitem)
        {
            UserProperties mailUserProperties = null;

            try
            {
                var pointer = 0;
                mailUserProperties = mailitem.UserProperties;
                for (var i = 1; i == mailUserProperties.Count; i++)
                {
                    if (mailUserProperties[i].Name == "KayakoTicketId")
                    {
                        pointer = i;
                    }
                }
                mailUserProperties.Remove(pointer);
                mailitem.Save();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (mailUserProperties != null)
                {
                    Marshal.ReleaseComObject(mailUserProperties);
                }
            }
        }
Example #6
0
        private static bool _ReformatDate(MailItem item)
        {
            CultureInfo provider = CultureInfo.InvariantCulture;
            DateTime    newDate  = DateTime.MinValue;
            string      dateMatch;
            Regex       regex = new Regex(@"\d\d\/\d\d\/\d\d\d\d");

            if (regex.IsMatch(item.HTMLBody))
            {
                dateMatch = regex.Match(item.HTMLBody).Value;
                newDate   = DateTime.ParseExact(dateMatch, "dd/MM/yyyy", provider);
            }
            else
            {
                regex = new Regex(@"((\w){3,6}day), 0\d ((Jan|Febr)uary|Ma(rch|y)|A(pril|ugust)|Ju(ne|ly)|((Sept|Nov|Dec)em|Octo)ber) (\d){4}");
                if (regex.IsMatch(item.HTMLBody))
                {
                    dateMatch = regex.Match(item.HTMLBody).Value;
                    newDate   = DateTime.ParseExact(dateMatch, "dddd, dd MMMM yyyy", provider);
                }
                else
                {
                    return(false);
                }
            }

            string newDateString = newDate.ToString("dddd, d MMMM yyyy");

            item.HTMLBody = item.HTMLBody.Replace(dateMatch, newDateString);
            item.Save();
            return(true);
        }
        public static void AddUserProperty(MailItem mailitem, string ticketid)
        {
            UserProperties mailUserProperties = null;
            UserProperty   mailUserProperty   = null;

            try
            {
                mailUserProperties = mailitem.UserProperties;
                mailUserProperty   = mailUserProperties.Add("KayakoTicketId", OlUserPropertyType.olText, true, 1);
                // Where 1 is OlFormatText (introduced in Outlook 2007)
                mailUserProperty.Value = ticketid;
                mailitem.Save();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (mailUserProperty != null)
                {
                    Marshal.ReleaseComObject(mailUserProperty);
                }
                if (mailUserProperties != null)
                {
                    Marshal.ReleaseComObject(mailUserProperties);
                }
            }
        }
Example #8
0
        public static void getNextItemFromConversation(object email, Conversation conv, String category)
        {
            SimpleItems items = conv.GetChildren(email);

            if (items.Count > 0)
            {
                foreach (object myItem in items)
                {
                    if (myItem is MailItem)
                    {
                        MailItem mailItem           = myItem as MailItem;
                        string   existingCategories = mailItem.Categories;
                        if (string.IsNullOrEmpty(existingCategories))
                        {
                            mailItem.Categories = category;
                        }
                        else
                        {
                            mailItem.Categories = existingCategories + ", " + category;
                        }
                        mailItem.Categories = RemoveUnnecessaryCategories(mailItem.Categories, category);
                        mailItem.Save();
                    }
                    getNextItemFromConversation(myItem, conv, category);
                }
            }
        }
        public static void CreateDraft(string sender, string subject, string body, string recipient, string attachment)
        {
            try
            {
                if (oApp == null)
                {
                    oApp = new Application();
                }
                // Create the Outlook application by using inline initialization.
                // Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();

                //Create the new message by using the simplest approach.
                MailItem oMsg = (MailItem)oApp.CreateItem(OlItemType.olMailItem);

                //Add a recipient.
                // TODO: Change the following recipient where appropriate.
                Recipient oRecip = (Recipient)oMsg.Recipients.Add(recipient);
                oRecip.Resolve();

                //Set the basic properties.
                oMsg.Subject = subject;
                oMsg.Body    = body;

                //Add an attachment.
                // TODO: change file path where appropriate
                Attachment oAttach;
                FileInfo   f = new FileInfo(attachment);
                if (f.Exists == true)
                {
                    String sDisplayName = f.Name;
                    int    iPosition    = (int)oMsg.Body.Length + 1;
                    int    iAttachType  = (int)OlAttachmentType.olByValue;
                    oAttach = oMsg.Attachments.Add(attachment, iAttachType, iPosition, sDisplayName);
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show(string.Format("Attachment dose not exist '{0}'", attachment));
                    return;
                }
                // If you want to, display the message.
                // oMsg.Display(true);  //modal

                //Send the message.
                oMsg.Save();
                //oMsg.Send();

                //Explicitly release objects.
                oRecip  = null;
                oAttach = null;
                oMsg    = null;
                oApp    = null;
            }

            // Simple error handler.
            catch (System.Exception e)
            {
                System.Windows.Forms.MessageBox.Show(string.Format("{0} Exception caught: ", e));
                // Console.WriteLine("{0} Exception caught: ", e);
            }
        }
Example #10
0
        public static void oznaczCalaKonwersacjeKategoria(MailItem email, string category)
        {
            Conversation conv        = email.GetConversation();
            SimpleItems  simpleItems = conv.GetRootItems();

            foreach (object item in simpleItems)
            {
                if (item is MailItem)
                {
                    MailItem mail = item as MailItem;
                    string   existingCategories = mail.Categories;
                    if (string.IsNullOrEmpty(existingCategories))
                    {
                        mail.Categories = category;
                    }
                    else
                    {
                        mail.Categories = existingCategories + ", " + category;
                    }
                    mail.Categories = RemoveUnnecessaryCategories(mail.Categories, category);
                    mail.Save();
                }

                getNextItemFromConversation(item, conv, category);
            }
        }
Example #11
0
        public static UserProperty GetCustomNotestUserProperty(MailItem mailItem)
        {
            
            {
                UserProperty _userProperty = mailItem.UserProperties
                    .Find(Notes_CustomNotes, true /* search custom fields */);

                if (_userProperty == null)
                {
                    // Add the UP because it does not exist
                    mailItem.UserProperties.Add(
                        Notes_CustomNotes,             // Name
                        OlUserPropertyType.olText,      // Type
                        false,                          // Add it to the folder
                        0);                             // Display Format

                    _userProperty = mailItem.UserProperties
                        .Find(Notes_CustomNotes,
                        true /* search custom fields */);
                    mailItem.Save();
                }

                return _userProperty;
            }
        }
Example #12
0
        internal static int pushEmails(Selection selectedItems)
        {
            List <Email> emailList = new List <Email>();

            for (int i = 1; i < selectedItems.Count + 1; i++)
            {
                Object currentSelected = selectedItems[i];

                if (currentSelected is MailItem)
                {
                    Email emailObj = convertMailItem(currentSelected as MailItem);
                    emailList.Add(emailObj);
                }
            }

            if (emailList.Count > 0)
            {
                String jsonString = JsonConvert.SerializeObject(emailList, Formatting.Indented);
                //MessageBox.Show("JSON: " + jsonString);

                byte[] postData = new ASCIIEncoding().GetBytes(String.Format("emails={0}", jsonString));

                string response = makeWebRequest(Globals.ThisAddIn.endpoint + PUSH_EMAILS_METHOD,
                                                 "POST",
                                                 postData,
                                                 Globals.ThisAddIn.username,
                                                 Globals.ThisAddIn.password);

                ASPECResponse aspecResponse = JsonConvert.DeserializeObject <ASPECResponse>(response);

                if (aspecResponse != null && aspecResponse.success == 1)
                {
                    for (int i = 1; i < selectedItems.Count + 1; i++)
                    {
                        Object   currentSelected = selectedItems[i];
                        MailItem email           = null;

                        if (currentSelected is MailItem)
                        {
                            email = currentSelected as MailItem;

                            if (email.UserProperties.Find(PUBLISHED_FLAG) == null)
                            {
                                email.UserProperties.Add(PUBLISHED_FLAG, OlUserPropertyType.olYesNo, true, true);
                            }
                            email.UserProperties[PUBLISHED_FLAG].Value = true;
                            email.Save();
                        }
                    }

                    return(emailList.Count);
                }
                else
                {
                    throw new System.Exception("Bad response from ASPEC: " + (aspecResponse == null ? "null" : aspecResponse.success.ToString()));
                }
            }
            return(0);
        }
Example #13
0
 private void btnArchive_Click(object sender, EventArgs e)
 {
     try
     {
         bool flag = false;
         base.Enabled = false;
         this.Cursor  = Cursors.WaitCursor;
         foreach (object obj2 in Globals.ThisAddIn.Application.ActiveExplorer().Selection)
         {
             MailItem o = obj2 as MailItem;
             if (this.type == "SendArchive")
             {
                 o.Save();
             }
             if (this.tsResults.Nodes.Count > 0)
             {
                 if (this.traverseTree(this.tsResults, 0) > 0)
                 {
                     string emailId = this.archiveEmail(o);
                     if (emailId != "-1")
                     {
                         foreach (TreeNode node in this.checkedNodes)
                         {
                             this.createEmailRelationship(emailId, node);
                         }
                     }
                 }
                 else
                 {
                     flag = true;
                     MessageBox.Show("Error Archiving Email", "Error");
                 }
                 this.checkedNodes.Clear();
             }
             else
             {
                 flag = true;
                 MessageBox.Show("There are no search results.", "Error");
             }
             Marshal.ReleaseComObject(o);
         }
         base.Enabled = true;
         this.Cursor  = Cursors.Default;
         if (!flag)
         {
             if (settings.ShowConfirmationMessageArchive)
             {
                 MessageBox.Show(Globals.ThisAddIn.Application.ActiveExplorer().Selection.Count.ToString() + " Email has been successfully archived", "Success");
             }
             base.Close();
         }
     }
     catch (System.Exception exception)
     {
         MessageBox.Show("There was an error while archiving", "Error");
         base.Enabled = true;
         this.Cursor  = Cursors.Default;
     }
 }
Example #14
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();
        }
Example #15
0
 public void NewMessage(string to, string subject, string body)
 {
     mailItem         = Application.CreateItem(OlItemType.olMailItem);
     mailItem.To      = to;
     mailItem.Subject = subject;
     mailItem.Body    = body;
     mailItem.Display();
     mailItem.Save();
 }
Example #16
0
 private bool ExtractEmailAttachments(Application application, MailItem objMail, string folder, List <string> attachments)
 {
     if (!Directory.Exists(folder))
     {
         Directory.CreateDirectory(folder);
     }
     if (objMail.Attachments.Count > 0)
     {
         int count = objMail.Attachments.Count;
         int num2  = 1;
         while (true)
         {
             if (num2 > count)
             {
                 objMail.Save();
                 break;
             }
             if (!objMail.Attachments[num2].FileName.EndsWith(".eml") && !objMail.Attachments[num2].FileName.EndsWith(".msg"))
             {
                 if (attachments.Contains(objMail.Attachments[num2].FileName))
                 {
                     objMail.Attachments[num2].SaveAsFile(Path.Combine(folder, objMail.Attachments[num2].FileName));
                 }
             }
             else
             {
                 string path = Path.Combine(folder, num2 + "_" + objMail.Attachments[num2].FileName);
                 objMail.Attachments[num2].SaveAsFile(path);
                 MailItem item = application.Session.OpenSharedItem(path) as MailItem;
                 string   str2 = item.Subject.Replace(":", "");
                 int      num3 = item.Attachments.Count;
                 int      num4 = 1;
                 while (true)
                 {
                     if (num4 > num3)
                     {
                         if (attachments.Contains(item.Subject + "_Message_Body"))
                         {
                             this.ExtractEmailBody(item, folder, string.Concat(new object[] { num2, "_0_", str2, "_Message_Body.rtf" }));
                         }
                         break;
                     }
                     if (attachments.Contains(item.Subject + "_" + item.Attachments[num4].FileName))
                     {
                         object[] objArray = new object[] { num2, "_", num4, "_", str2, "_", item.Attachments[num4].FileName };
                         item.Attachments[num4].SaveAsFile(Path.Combine(folder, string.Concat(objArray)));
                     }
                     num4++;
                 }
             }
             num2++;
         }
     }
     return(true);
 }
Example #17
0
        /// <summary>
        /// Email Processing
        /// </summary>
        /// <param name="templatePath"></param>
        /// <param name="subject"></param>
        /// <param name="toMail"></param>
        /// <param name="ccMail"></param>
        /// <param name="bccMail"></param>
        /// <param name="values"></param>
        /// <param name="attachFilePaths"></param>
        /// <param name="sendMail"></param>
        /// <returns></returns>
        internal bool EmailFromTemplate(
            string templatePath,
            string subject,
            string toMail,
            string ccMail,
            string bccMail,
            Dictionary <string, string> values,
            List <string> attachFilePaths,
            bool sendMail)
        {
            try
            {
                Folder m_draftFolder = App.Session.GetDefaultFolder(
                    OlDefaultFolders.olFolderDrafts) as Folder;
                MailItem m_mail = App.CreateItemFromTemplate(templatePath, m_draftFolder) as MailItem;
                if (m_mail != null)
                {
                    m_mail.Subject = subject;
                    m_mail.To      = toMail;
                    m_mail.CC      = ccMail;
                    m_mail.BCC     = bccMail;

                    foreach (var x in attachFilePaths)
                    {
                        m_mail.Attachments.Add(x);
                    }

                    // Replace %%%% contents with matches in the body
                    StringBuilder m_sb = new StringBuilder(m_mail.HTMLBody);
                    foreach (var x in values)
                    {
                        m_sb.Replace(string.Format("%%{0}%%", x.Key.ToUpper()), x.Value);
                    }
                    m_mail.HTMLBody = m_sb.ToString();

                    if (sendMail)
                    {
                        m_mail.Send();
                    }
                    else
                    {
                        m_mail.Save();
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                // way too lazy to do anything here
            }
            return(false);
        }
        public string IncomeMail(MailItem mailItem)
        {
            mailItem.UnRead = true;
            mailItem.Save();

            Outlook.Folder selectedFolder = StartDialogService();
            if (selectedFolder != null)
            {
                MailItem copyMail = mailItem.Copy();
                copyMail.Move(selectedFolder);
            }
            return(mailItem.EntryID);
        }
Example #19
0
        private void AfterTraining_Ham(MailItem mi)
        {
            if (this.config.AfterTraining_Ham_DoDelete)
            {
                // delete mail
                mi.Delete();
            }
            else
            {
                // mark as read
                if (this.config.AfterTraining_Ham_MarkAsRead)
                {
                    mi.UnRead = false;
                    mi.Save();
                }

                // prefix - it's ham, so remove the prefix
                if (this.config.AfterTraining_Ham_DoPrefix)
                {
                    // mi.Subject = this.config.AfterTraining_Ham_PrefixWith + " " + mi.Subject;
                    mi.Subject = mi.Subject.Replace(this.config.AfterTraining_Ham_PrefixWith, "");
                    mi.Save();
                }

                // move
                if (this.config.AfterTraining_Ham_DoMove)
                {
                    if (this.config.AfterTraining_Ham_MoveTo != "")
                    {
                        mi.Move(this.mailparser.getFolderByName(this.config.AfterTraining_Ham_MoveTo));
                    }
                }
                else
                {
                    // do nothing
                }
            }
        }
        public static MailItem GetTestMail(Application app)
        {
            MailItem mail = app.CreateItem(OlItemType.olMailItem);

            {
                mail.To      = "*****@*****.**";
                mail.Subject = "Test";
                mail.Body    = "Some plain text for this body!";
            }

            mail.Save();

            return(mail);
        }
Example #21
0
        public static void MoveMessage(MailMessage message, string folderPath, string account)
        {
            MAPIFolder folder = GetFolder(folderPath, account);

            if (folder == null)
            {
                throw new ArgumentException("找不到目录");
            }
            string text = message.Headers["Uid"];

            if (string.IsNullOrEmpty(text))
            {
                throw new ArgumentException("非法邮件消息");
            }
            MailItem    mailItem    = null;
            MailItem    mailItem2   = null;
            Application application = null;

            try
            {
                application = InitOutlook();
                mailItem    = (dynamic)application.Session.GetItemFromID(text, Type.Missing);
                if (mailItem != null)
                {
                    mailItem2 = (mailItem.Move(folder) as MailItem);
                    mailItem2.Save();
                }
            }
            finally
            {
                if (folder != null)
                {
                    Marshal.ReleaseComObject(folder);
                }
                if (mailItem != null)
                {
                    Marshal.ReleaseComObject(mailItem);
                }
                if (mailItem2 != null)
                {
                    Marshal.ReleaseComObject(mailItem2);
                }
                if (application != null)
                {
                    Marshal.ReleaseComObject(application);
                }
            }
        }
Example #22
0
        // Event Handler for Remove Button
        public void OnRemoveButton(Office.IRibbonControl control)
        {
            Explorer explorer = Globals.ThisAddIn.Application.ActiveExplorer();
            MailItem mailItem = null;

            if (explorer != null && explorer.Selection != null && explorer.Selection.Count > 0)
            {
                object item = explorer.Selection[1];
                if (item is MailItem)
                {
                    mailItem = item as MailItem;
                }
            }

            if (mailItem != null)
            {
                string senderEmail = "";

                if (mailItem.SenderEmailType == "EX")
                {
                    // Exchange email address - ignore

                    string[] directoryParts = mailItem.SenderEmailAddress.Split('=');
                    if (directoryParts.Length > 1)
                    {
                        senderEmail = directoryParts[directoryParts.Length - 1].ToLower();
                    }
                }
                else
                {
                    senderEmail = mailItem.SenderEmailAddress;

                    int successCode = DeletePhishingEmail(senderEmail);

                    if (successCode > 0)
                    {
                        MessageBox.Show("'" + senderEmail + "' was successfully removed from the list of phishing email addresses.");

                        if (mailItem.Categories != null)
                        {
                            mailItem.Categories = mailItem.Categories.Replace("Dangerous sender!  Do not open links click images or open attachments.", "");
                            mailItem.Save();
                        }
                    }
                }
            }
        }
        public void AddNewCustomActions(MailItem mailItem)
        {
            string[] newCustomActions = { CreateWorkItem };
            foreach (string customAction in newCustomActions)
            {
                if (mailItem.Actions[customAction] == null)
                {
                    Microsoft.Office.Interop.Outlook.Action newAction;
                    newAction         = mailItem.Actions.Add();
                    newAction.Name    = customAction;
                    newAction.ShowOn  = OlActionShowOn.olMenu;
                    newAction.Enabled = true;
                    mailItem.Save();
                }
            }

            mailItem.CustomAction += new ItemEvents_10_CustomActionEventHandler(item_CustomAction);
        }
Example #24
0
        public void SendReport(MailItem reportedMailItem)
        {
            Helpers.SetUserProperty(reportedMailItem, Constants.EMAIL_REPORTED, true);
            Helpers.SetUserProperty(reportedMailItem, Constants.EMAIL_REPORTED_DATE, DateTime.Now);
            reportedMailItem.Save();

            CreateAndSendReport(reportedMailItem);

            if (Configuration.DeleteAfterReport)
            {
                reportedMailItem.Delete();
            }
            else if (Configuration.MoveToJunkAfterReport)
            {
                MAPIFolder junkFolder = Application.ActiveExplorer().Session.GetDefaultFolder(OlDefaultFolders.olFolderJunk);
                reportedMailItem.Move(junkFolder);
            }
        }
Example #25
0
 //configuración de correo Outllok
 public void senmail(string destinatarios, string mensaje, string Asunto)
 {
     try
     {
         // string[] cr = destinatarios.Split(";");
         Application oApp1 = new Application();
         MailItem    item  = (MailItem)oApp1.CreateItem(OlItemType.olMailItem);
         item.BCC    += destinatarios;
         item.Subject = Asunto;
         item.Body    = mensaje;
         //item.Display(true);
         item.Save();
         item.Send();
     }
     catch (System.Exception ex)
     {
         throw (ex);
     }
 }
        public void DoAction_MoveToFolder_MovesMail()
        {
            //Arrange
            string   uuid     = System.Guid.NewGuid().ToString();
            MailItem testMail = Factory.GetTestMail(_app);;

            testMail.Body = uuid;
            testMail.Save();
            MailItem_ID  mailID   = new MailItem_ID(testMail);
            RuleCriteria criteria = GetDefaultCriteria();
            {
                criteria.ResultingAction = new OlDocPublish.RulesMock.RuleAction[] { OlDocPublish.RulesMock.RuleAction.MoveToFolder };
                criteria.ActionArg       = "Test Folder";
            }

            Folder targetFolder = _app.Session.GetDefaultFolder(OlDefaultFolders.olFolderInbox).Parent.Folders["Test Folder"];
            bool   expected     = true;
            bool   actual       = false;

            //Act
            criteria.DoAction(mailID);

            //Assert
            foreach (MailItem mail in targetFolder.Items)
            {
                if (mail.Body.Contains(uuid))
                {
                    actual = true;
                }
            }

            if (targetFolder == null ||
                targetFolder.Items.Count == 0)
            {
                Assert.Fail();
            }

            Assert.AreEqual(expected, actual);
        }
Example #27
0
        public void addFileToEmail(string newPathWay, string today)
        {
            string[] emailsList =
            {
                "MSPP",
                "Medtronic (Spare Parts) Report",
                "Hi All",
                "", /// Email to TO:
                ""  /// Emails to CC:
            };

            Application outlookApp = new Application();
            MailItem    mailItem   = outlookApp.CreateItem(OlItemType.olMailItem);

            string bigLogo     = @"V:\Warehouses\Tax Warehouse\logos\BigLogo.png";
            string bigLogoLink = "sslirl.com";

            mailItem.Attachments.Add(newPathWay); /// Excel report to attach
            mailItem.To      = emailsList[3];
            mailItem.CC      = emailsList[4];
            mailItem.Subject = emailsList[1] + " " + today;

            mailItem.HTMLBody = string.Format("<body>" + emailsList[2] + "," +
                                              "<p>Please find attached " + emailsList[1] +
                                              ".</p>" +
                                              "<p>Regards,<br>" +
                                              "<span style=\"font-size: 12.0pt;color:navy\"> Your Name Here </span>" +
                                              "<br><span style=\"font-size: 8.0pt;color:#1F497D\">Source & Supply Logistics Ltd</span>" +
                                              "<br><span style=\"font-size: 8.0pt;color:#1F497D\">IDA Business & Technology Park</span>" +
                                              "<br><span style=\"font-size: 8.0pt;color:#1F497D\"" + ">Parkmore West</span>" +
                                              "<br><span style=\"font-size: 8.0pt;color:#1F497D\">Galway, Ireland.</span>" +
                                              "<br><span style=\"font-size: 9.0pt;color:navy;font-weight:bold\">Phone: </span>" + "  " +
                                              "<span style=\"font-size: 9.0pt;color:navy;font-weight:bold\">Fax: </span>" +
                                              "<br><span style=\"font-size: 9.0pt;color:navy;font-weight:bold\">Email:</span> " +
                                              "<span style=\"font-size: 9.0pt;color:blue;font-weight:bold\"> Your Email Here </span>" +
                                              "<p></body><a href=\"{1}\"><img src=\"{0}\"></a></p>", bigLogo, bigLogoLink);
            mailItem.Save();
        }
Example #28
0
        public void senmail2(string destinatarios, string mensaje, string Asunto, string archivo, string para)
        {
            try
            {
                // string[] cr = destinatarios.Split(";");
                Application oApp1 = new Application();
                MailItem    ema   = (MailItem)oApp1.CreateItem(OlItemType.olMailItem);
                //ema. = new MailAddress(para);
                ema.To      = para;
                ema.Subject = Asunto;
                ema.Body    = mensaje;

                ema.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceHigh;
                System.Net.Mail.Attachment archin = new System.Net.Mail.Attachment(archivo);
                ema.Attachments.Add(archivo, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
                ema.Save();
                //item.Display(true);
                ema.Send();
            }
            catch (System.Exception ex)
            {
                throw (ex);
            }
        }
Example #29
0
    /// <summary>
    /// Sends report to PM.
    /// </summary>
    /// <returns>Was the report sended.</returns>
    protected bool SendReport()
    {
        try
        {
            if (string.IsNullOrEmpty(tbTo.Text)
                || string.IsNullOrEmpty(tbSubject.Text)
                || string.IsNullOrEmpty(tbMessage.Text)
                || !Regex.IsMatch(tbTo.Text, valToRegex.ValidationExpression))
                return false;

            Debug.Assert( CurrentUser != null );
            if (CurrentUser.ID != null && !string.IsNullOrEmpty(CurrentUser.PrimaryEMail))
            {
                MailItem item = new MailItem
                                    {
                                        FromAddress = CurrentUser.PrimaryEMail,
                                        ToAddress = tbTo.Text,
                                        Subject = tbSubject.Text,
                                        Body = tbMessage.Text,
                                        MessageType = ((int) MailTypes.UserReport)
                                    };
                item.Save();
            }

            return true;
        }
        catch( Exception ex )
        {
            ConfirmIt.PortalLib.Logger.Logger.Instance.Error(ex.Message, ex);
            return false;
        }
    }
Example #30
0
        public void DoesRequireCompare(MailItem original, MailItem modified)
        {
            try
            {
                Logger.LogInfo("EMAILTRACKING: Working out if there is anything to compare or not!");
                new PropertyInfo(modified).LogUserProperties();

                Dictionary<string, Attachment> modAttachs = GetAttachments(modified.Attachments.OfType<Attachment>());
                Dictionary<string, Attachment> origAttachs = GetAttachments(original.Attachments.OfType<Attachment>());

                var compareFiles = Stemmer.GetRelated(origAttachs.Keys.ToArray(), modAttachs.Keys.ToArray());

                // Make sure selection does not send information here.
                UserProperty prop = modified.UserProperties.Find(NamedProperties.CompareRequired, true);
                prop.Value = compareFiles.Count > 0 ? NamedProperties.CompareProcess : NamedProperties.CompareNothing;

                UserProperty up = modified.UserProperties.Add(NamedProperties.AttachmentNames, OlUserPropertyType.olText, true);
                UserProperty howManyLeftProp = modified.UserProperties.Find(NamedProperties.CompareHowMany, true) ?? modified.UserProperties.Add(NamedProperties.CompareHowMany,
                                                                                                                                        OlUserPropertyType.olText,
                                                                                                                                        true);
                howManyLeftProp.Value = compareFiles.Count.ToString();


                foreach (var pair in compareFiles)
                {
                    ComparisonInformation comparison = NewComparisonInformation(origAttachs[pair.Key], modAttachs[pair.Value], original.EntryID, modified.EntryID);
                    comparison.Completed += OnComparisonCompleted;

                    string val = (up.Value as string);
                    if (val != null)
                    {
                        if (!val.Contains(pair.Key))
                        {
                            up.Value += pair.Key + ";";
                        }
                    }

                    modified.Save();

                    AddToQueue(comparison);
                }
            }
            catch (SystemException e)
            {
                Logger.LogInfo("EMAILTRACKING: DoesRequireCompare threw - " + e.ToString());
            }
        }
Example #31
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);
                    }
                }
            }
        }
Example #32
0
        private void GetAttachmentsFromConversation(MailItem mailItem)
        {
            if (mailItem == null)
            {
                return;
            }

            if (mailItem.Attachments.CountNonEmbeddedAttachments() > 0)
            {
                return;
            }

            System.Collections.Generic.Stack <MailItem> st = new System.Collections.Generic.Stack <MailItem>();

            // Determine the store of the mail item.
            Outlook.Folder folder = mailItem.Parent as Outlook.Folder;
            Outlook.Store  store  = folder.Store;
            if (store.IsConversationEnabled == true)
            {
                // Obtain a Conversation object.
                Outlook.Conversation conv = mailItem.GetConversation();
                // Check for null Conversation.
                if (conv != null)
                {
                    // Obtain Table that contains rows
                    // for each item in the conversation.
                    Outlook.Table table = conv.GetTable();
                    _logger.Debug("Conversation Items Count: " + table.GetRowCount().ToString());
                    _logger.Debug("Conversation Items from Root:");

                    // Obtain root items and enumerate the conversation.
                    Outlook.SimpleItems simpleItems = conv.GetRootItems();
                    foreach (object item in simpleItems)
                    {
                        // In this example, enumerate only MailItem type.
                        // Other types such as PostItem or MeetingItem
                        // can appear in the conversation.
                        if (item is Outlook.MailItem)
                        {
                            Outlook.MailItem mail     = item as Outlook.MailItem;
                            Outlook.Folder   inFolder = mail.Parent as Outlook.Folder;
                            string           msg      = mail.Subject + " in folder [" + inFolder.Name + "] EntryId [" + (mail.EntryID.ToString() ?? "NONE") + "]";
                            _logger.Debug(msg);
                            _logger.Debug(mail.Sender);
                            _logger.Debug(mail.ReceivedByEntryID);

                            if (mail.EntryID != null && (mail.Sender != null || mail.ReceivedByEntryID != null))
                            {
                                st.Push(mail);
                            }
                        }
                        // Call EnumerateConversation
                        // to access child nodes of root items.
                        EnumerateConversation(st, item, conv);
                    }
                }
            }

            while (st.Count > 0)
            {
                MailItem it = st.Pop();

                if (it.Attachments.CountNonEmbeddedAttachments() > 0)
                {
                    //_logger.Debug(it.Attachments.CountNonEmbeddedAttachments());

                    try
                    {
                        if (mailItem.IsMailItemSignedOrEncrypted())
                        {
                            if (MessageBox.Show(null, "Es handelt sich um eine signierte Nachricht. Soll diese für die Anhänge ohne Zertifikat dupliziert werden?", "Nachricht duplizieren?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                            {
                                mailItem.Close(OlInspectorClose.olDiscard);
                                mailItem = mailItem.Copy();
                                mailItem.Unsign();
                                mailItem.Save();
                                mailItem.Close(OlInspectorClose.olDiscard);
                                mailItem.Save();
                            }
                            else
                            {
                                st.Clear();
                                break;
                            }
                        }

                        mailItem.CopyAttachmentsFrom(it);
                        mailItem.Save();
                    }
                    catch (System.Exception ex)
                    {
                        //mailItem.Close(OlInspectorClose.olDiscard);
                        MessageBox.Show(ex.Message);
                    }

                    st.Clear();
                }
            }
            st.Clear();

            Marshal.ReleaseComObject(mailItem);
        }
Example #33
0
        private void CreateNewMailToSecurityTeam(IRibbonControl control)
        {
            Selection selection =
                Globals.ThisAddIn.Application.ActiveExplorer().Selection;

            if (selection.Count == 1)                 // Check that selection is not empty.
            {
                object   selectedItem = selection[1]; // Index is one-based.
                Object   mailItemObj  = selectedItem as Object;
                MailItem mailItem     = null;         // selectedItem as MailItem;
                if (selection[1] is Outlook.MailItem)
                {
                    mailItem = selectedItem as MailItem;
                }

                MailItem tosend = (MailItem)Globals.ThisAddIn.Application.CreateItem(OlItemType.olMailItem);
                tosend.Attachments.Add(mailItemObj);

                #region create mail from default
                try
                {
                    tosend.To      = Properties.Settings.Default.Security_Team_Mail;
                    tosend.Subject = "[User Alert] Suspicious mail";

                    tosend.CC  = Properties.Settings.Default.Security_Team_Mail_cc;
                    tosend.BCC = Properties.Settings.Default.Security_Team_Mail_bcc;

                    #region retrieving message header
                    string allHeaders = "";
                    if (selection[1] is Outlook.MailItem)
                    {
                        string[] preparedByArray = mailItem.Headers("X-PreparedBy");
                        string   preparedBy;
                        if (preparedByArray.Length == 1)
                        {
                            preparedBy = preparedByArray[0];
                        }
                        else
                        {
                            preparedBy = "";
                        }
                        allHeaders = mailItem.HeaderString();
                    }
                    else
                    {
                        string typeFound = "unknown";
                        typeFound = (selection[1] is Outlook.MailItem) ? "MailItem" : typeFound;

                        if (typeFound == "unknown")
                        {
                            typeFound = (selection[1] is Outlook.MeetingItem) ? "MeetingItem" : typeFound;
                        }

                        if (typeFound == "unknown")
                        {
                            typeFound = (selection[1] is Outlook.ContactItem) ? "ContactItem" : typeFound;
                        }

                        if (typeFound == "unknown")
                        {
                            typeFound = (selection[1] is Outlook.AppointmentItem) ? "AppointmentItem" : typeFound;
                        }

                        if (typeFound == "unknown")
                        {
                            typeFound = (selection[1] is Outlook.TaskItem) ? "TaskItem" : typeFound;
                        }

                        allHeaders = "Selected Outlook item was not a mail (" + typeFound + "), no header extracted";
                    }

                    #endregion

                    string SwordPhishURL = SwordphishObject.SetHeaderIDtoURL(allHeaders);

                    if (SwordPhishURL != SwordphishObject.NoHeaderFound)
                    {
                        string SwordPhishAnswer = SwordphishObject.SendNotification(SwordPhishURL);
                    }
                    else
                    {
                        tosend.Body  = "Hello, I received the attached email and I think it is suspicious";
                        tosend.Body += "\n";
                        tosend.Body += "I think this mail is malicious for the following reasons:";
                        tosend.Body += "\n";
                        tosend.Body += "Please analyze and provide some feedback.";
                        tosend.Body += "\n";
                        tosend.Body += "\n";

                        tosend.Body += GetCurrentUserInfos();

                        tosend.Body += "\n\nMessage headers: \n--------------\n" + allHeaders + "\n\n";

                        tosend.Save();
                        tosend.Display();
                    }
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Using default template" + ex.Message);

                    MailItem mi = (MailItem)Globals.ThisAddIn.Application.CreateItem(OlItemType.olMailItem);
                    mi.To      = Properties.Settings.Default.Security_Team_Mail;
                    mi.Subject = "Security addin error";
                    String txt = ("An error occured, please notify your security contact and give him/her the following information: " + ex);
                    mi.Body = txt;
                    mi.Save();
                    mi.Display();
                }
            }
            else if (selection.Count < 1)   // Check that selection is not empty.
            {
                MessageBox.Show("Please select one mail.");
            }
            else if (selection.Count > 1)
            {
                MessageBox.Show("Please select only one mail to be raised to the security team.");
            }
            else
            {
                MessageBox.Show("Bad luck... this case has not been identified by the dev");
            }
        }
Example #34
0
 private bool IsUpdateMessage(MailItem mail)
 {
     if (!mail.Subject.Equals(UPDATE_SUBJECT,
         StringComparison.CurrentCultureIgnoreCase)) return false;
     var folder = (Folder)mail.Parent;
     if (folder == null) return false;
     var store = Session.GetStoreFromID(folder.StoreID);
     Logger.Verbose("IsUpdateMessage", string.Format(
         "evaluating {0} in {1}\\{2}",
         mail.Subject,
         store.DisplayName,
         folder.Name));
     if (!IsInOwnedStore(folder)) return false;
     //extract data from internet message header
     var pointer = "";
     var sender = "";
     var server = "";
     var port = "";
     Utils.ReadUpdateHeaders(mail, ref sender, ref pointer, ref server, ref port);
     SearchForUpdatedMessage(sender, pointer, server, port, folder.StoreID);
     //try to delete it directly (may not work)
     try
     {
         mail.UnRead = false;
         mail.Move(store.GetDefaultFolder(OlDefaultFolders.olFolderDeletedItems));
         mail.Save();
     }
     catch
     {
         //couldn't delete - probably locked
         //mark as 'read'
         mail.UnRead = false;
         mail.Save();
     }
     return true;
 }
Example #35
0
        private void AfterTraining_Spam(MailItem mi)
        {
            if (this.config.AfterTraining_Spam_DoDelete)
            {
                // delete mail
                mi.Delete();
            }
            else
            {
                // mark as read
                if (this.config.AfterTraining_Spam_MarkAsRead)
                {
                    mi.UnRead = false;
                    mi.Save();
                }

                // prefix
                if (this.config.AfterTraining_Spam_DoPrefix)
                {
                    mi.Subject = this.config.AfterTraining_Spam_PrefixWith + " " + mi.Subject;
                    mi.Save();
                }

                // move
                if (this.config.AfterTraining_Spam_DoMove)
                {
                    if (this.config.AfterTraining_Spam_MoveTo != "")
                    {
                        mi.Move(this.mailparser.getFolderByName(this.config.AfterTraining_Spam_MoveTo));
                    }
                }
                else
                {
                    // do nothing
                }
            }
        }