Example #1
0
        // Although NewMailEx event is triggered before outlook rule processing, these 2 run asynchronized,
        // so the rule processing doesn't guarentee to run "after" the completion of NewMailEx handler.
        // And NewMailEx event will not be triggered for every new mail if a lot of new mails coming in a short period of time.
        //
        // so the most reliable way to process every new mail is to add an outlook email rule to "run a script" for
        // every new mail.
        //
        // put the following function into outlook vba editor, under "TheOutlookSession", and create an email rule
        // to "run a script" this one.
        //
        // Enable "run a script" in Outlook 2013:
        // Create a DWORD "EnableUnsafeClientMailRules" under
        // HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Outlook\Security, and set to 1
        //
        // Public Sub XXX(Item As Outlook.MailItem)
        //     Header = Item.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x007D001E")
        //     Pos = InStr(Header, "X-Mailer: nodemailer")
        //     If Pos Then
        //         Item.Categories = "No need to popup new mail alarm"
        //         Item.Save
        //     End If
        // End Sub
        private void ApplicationNewMailEx(string EntryIDCollection)
        {
            Outlook.NameSpace nameSpace = Application.GetNamespace("MAPI");
            string[]          entryIds  = EntryIDCollection.Split(',');
            for (int i = 0; i < entryIds.Length; ++i)
            {
                Outlook.MailItem mailItem = null;

                try {
                    mailItem = nameSpace.GetItemFromID(entryIds[i]) as Outlook.MailItem;
                } catch (COMException) {
                }

                if (mailItem != null)
                {
                    FilterEmailUtil.FilterOutUnwantedEmail(mailItem);
                    if (Config.AutoBackupEmailFromMe == true && Util.GetSenderSMTPAddress(mailItem) == Config.MyEmailAddress)
                    {
                        BackupEmailUtil.MarkEmailReadAndClearAllCategories(mailItem);
                        EmailFlagUtil.FlagEmail(mailItem);
                        BackupEmailUtil.BackupEmail(mailItem);
                    }
                }
            }
        }
Example #2
0
        private void Application_NewMailEx(string entryIdItem)
        {
            Outlook.NameSpace ns = Application.GetNamespace("MAPI");
            var item             = ns.GetItemFromID(entryIdItem);

            try
            {
                if (item is Outlook.MailItem)
                {
                    var processor  = new MailItemProcessor(item as Outlook.MailItem);
                    var controller = new LogResultsTaskController();
                    processor.NewResultsAvailable      += controller.OnNewResultsAvailable;
                    controller.LogResultsTaskCompleted += SendSuccessMail;
                    processor.ProcessMailRule();
                    return;
                }
            }
            catch (AggregateException ex)
            {
                var p = from innerEx in ex.InnerExceptions
                        select innerEx.Message;
                string errorMessages = String.Join <string>("\n", p.ToList());
                SendErrorMail(errorMessages);
            }
            catch (Exception ex)
            {
                SendErrorMail(ex.Message);
            }
        }
Example #3
0
        private void olApp_NewMail(String entryIDCollection)
        {
            Outlook.NameSpace  outlookNS = this.Application.GetNamespace("MAPI");
            Outlook.MAPIFolder mFolder   = this.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
            Outlook.MailItem   mail;

            try
            {
                mail            = (Outlook.MailItem)outlookNS.GetItemFromID(entryIDCollection, Type.Missing);
                mail.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
//                    mail.HTMLBody = "<html><body dir='auto'>" + mail.HTMLBody + "</body></html>";
                WebBrowser browser = new WebBrowser();
                browser.ScriptErrorsSuppressed = true;
                browser.DocumentText           = mail.HTMLBody;
                browser.Document.OpenNew(true);
                browser.Document.Write(mail.HTMLBody);
                browser.Refresh();
                HtmlDocument doc = browser.Document;
                SetDirections(doc);
                mail.HTMLBody = doc.Body.InnerHtml;
                Console.WriteLine(mail.HTMLBody);
                mail.Save();
            }
            catch
            { }
        }
Example #4
0
        public Email GetMessage(string entryID)
        {
            // pull the message
            Outlook.MailItem mi = (_nameSpace.GetItemFromID(entryID, "") as Outlook.MailItem);

            if (mi != null)
            {
                string body;

                // if it's a plain format message, wrap it in <pre> tags for nice output
                if (mi.BodyFormat == Outlook.OlBodyFormat.olFormatPlain)
                {
                    body = "<pre>" + mi.Body + "</pre>";
                }
                else
                {
                    body = mi.HTMLBody;
                }

                return(new Email(mi.EntryID, mi.SenderEmailAddress, mi.SenderName, mi.Subject, mi.ReceivedTime, mi.Size, body));
            }
            else
            {
                return(null);
            }
        }
        public static void RemoveFormFromPersonalFormsLibrary(string name)
        {
            bool formFound = false;

            Outlook.Table olTable;
            Outlook.Row   olRow;
            string        searchFilter;

            if (null == m_Application)
            {
                Initialise();
            }
            try
            {
                Outlook.MAPIFolder olFolder = GetCommonViewsFolder();
                if (null != olFolder)
                {
                    searchFilter = "[MessageClass] = \"IPM.Microsoft.FolderDesign.FormsDescription\"";
                    olTable      = olFolder.GetTable(searchFilter, Outlook.OlTableContents.olHiddenItems);
                    olTable.Columns.Add(PR_DISPLAY_NAME);
                    olTable.Columns.Add(SEARCH_FORM_MESSAGECLASS);
                    olTable.Columns.Add(PR_LONG_TERM_ENTRYID_FROM_TABLE);
                    olTable.Restrict(searchFilter);
                    while (!olTable.EndOfTable)
                    {
                        olRow = olTable.GetNextRow();
                        if (name.ToLower() == olRow[PR_DISPLAY_NAME].ToString().ToLower())
                        {
                            formFound = true;
                            byte[] entryId = olRow[PR_LONG_TERM_ENTRYID_FROM_TABLE];
                            string temp    = "";
                            for (int i = 0; i < entryId.Length; i++)
                            {
                                temp += entryId[i].ToString("X2");
                            }
                            object item = m_NameSpace.GetItemFromID(temp, olFolder.StoreID);
                            if (item is Outlook.StorageItem)
                            {
                                Outlook.StorageItem storageItem = item as Outlook.StorageItem;
                                storageItem.Delete();
                                Console.WriteLine("Form succesfully deleted. You might need to restart Outlook.");
                            }
                        }
                    }
                    if (!formFound)
                    {
                        Console.WriteLine("The form couldn't be found in the Personal Forms Library.");
                    }
                }
                ClearLocalFormCache();
            }
            catch (Exception exception)
            {
                Console.WriteLine("Unable to remove form. Error: " + exception.ToString());
            }
            finally
            {
            }
        }
Example #6
0
        public IItem GetItemFromID(string id)
        {
            using (ComRelease com = new ComRelease())
            {
                NSOutlook.NameSpace nmspace = com.Add(_item.Session);

                // Get the item; the wrapper manages it
                object o = nmspace.GetItemFromID(id);
                return(Mapping.Wrap <IItem>(o));
            }
        }
 private Outlook.AppointmentItem GetAppointment(string _appointmentEntryID, string _calendarStoreID)
 {
     try
     {
         Outlook.NameSpace ns = outlookApp.GetNamespace("MAPI"); // <-- Made it global, 2016.06.29 MGY
         return((Outlook.AppointmentItem)ns.GetItemFromID(_appointmentEntryID, _calendarStoreID));
     }
     catch (Exception x)
     {
         return(null);
     }
 }
Example #8
0
 void Application_NewMailEx(string anEntryId)
 {
     try
     {
         Outlook.NameSpace  outlookNS = Application.GetNamespace("MAPI");
         Outlook.MAPIFolder folder    = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
         Outlook.MailItem   mailItem  = (Outlook.MailItem)outlookNS.GetItemFromID(anEntryId, folder.StoreID);
         Timer t = new Timer(Bling2, mailItem, 2000, 0);
     }
     catch (Exception e)
     {
     }
 }
 private Outlook.AppointmentItem GetAppointment(string _appointmentEntryID, string _calendarStoreID)
 {
     try
     {
         //Outlook.Application outlookApp = new Outlook.Application();
         Outlook.NameSpace ns = outlookApp.GetNamespace("MAPI");
         return((Outlook.AppointmentItem)ns.GetItemFromID(_appointmentEntryID, _calendarStoreID));
     }
     catch (Exception x)
     {
         return(null);
     }
 }
Example #10
0
 private bool TryGetMailItem(string entryID, out Outlook.MailItem mailItem)
 {
     try
     {
         mailItem = defaultNamespace.GetItemFromID(entryID, Inbox.StoreID) as Outlook.MailItem;
         return(true);
     }
     catch // probably because it is not an email item
     {
         mailItem = null;
         return(false);
     }
 }
Example #11
0
 public static void openEmail(string emailid, string storeid)
 {
     Microsoft.Office.Interop.Outlook.Application otlApplication = new Microsoft.Office.Interop.Outlook.Application();
     try
     {
         Outlook.NameSpace otlNameSpace = otlApplication.GetNamespace("MAPI");
         Outlook.MailItem  mi           = (Outlook.MailItem)otlNameSpace.GetItemFromID(emailid, storeid);
         mi.Display(false);
     }
     catch (Exception exp)
     {
         throw new Exception("PST not there" + exp.Message);
     }
     finally { otlApplication = null; }
 }
Example #12
0
 private void Application_NewMailEx(string entryIDCollection)
 {
     try
     {
         dynamic          newITem  = outlookNameSpace.GetItemFromID(entryIDCollection);
         Outlook.MailItem mailItem = (Outlook.MailItem)newITem;
         if (mailItem != null)
         {
             ProcessMailItem(mailItem);
         }
         //
     }
     catch (Exception)
     {
         //throw ex;
     }
     //
     return;
     //
 }
Example #13
0
        ////log the emails which are sent to then pass on to the handler.
        //private static void LogSentEmail(object item)
        //{
        //    try
        //    {
        //        Outlook.MailItem email = (Outlook.MailItem)item;
        //        if (!emailsToIndex.Contains(email.EntryID))
        //        {
        //            emailsToIndex.Add(email.EntryID);
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        XLtools.LogException("LogEmailSent-Not an email", ex.ToString());
        //    }

        //}

        //////this timer will periodically check the list
        //public async Task PeriodicCheck()
        //{
        //    try
        //    {
        //        //timer = new System.Threading.Timer((e) =>
        //        //{
        //        //    PromptForEmails();
        //        //}, null, 0, 2000);
        //        while (true)
        //        {
        //            await Task.Delay(2000);
        //            PromptForEmails();
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show("Periodic check of e-mails sent has failed.  Please restart Outlook, if this problem persists please contact IT");
        //        XLtools.LogException("PeriodicCheck", ex.ToString());
        //    }

        //}

        //this then reviews the list and if appropriate runs the prompt method on the e-mails listed
        private static void PromptForEmails()
        {
            try
            {
                if (emailsToIndex.Count > 0)
                {
                    //MessageBox.Show(emailsToIndex.ToString());
                    foreach (string s in emailsToIndex.ToList())
                    {
                        Outlook.MailItem    item;
                        Outlook.Application app       = Globals.ThisAddIn.Application;
                        Outlook.NameSpace   nameSpace = app.GetNamespace("MAPI");
                        item = (Outlook.MailItem)nameSpace.GetItemFromID(s);
                        SentItemIndexer(item);
                    }
                }
            }
            catch (Exception ex)
            {
                XLtools.LogException("PromptforEmails", ex.ToString());
            }
        }
Example #14
0
        /// <summary>
        /// Метод ,отображающий Parent задачи ,если он есть.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonShowParent_Click(object sender, EventArgs e)
        {
            //срабатывает когда текущий контрол ,какая -нибудь таска
            if (Globals.ThisAddIn.selObject is Outlook.TaskItem)
            {
                Outlook.TaskItem taskItem =
                    (Globals.ThisAddIn.selObject as Outlook.TaskItem);
                try
                {
                    //проверяем есть ли у таски родитель
                    if (taskItem.UserProperties["Parent"] != null)
                    {
                        Outlook.NameSpace ns = Globals.ThisAddIn.Application.Session;

                        Outlook.TaskItem theitem = (Outlook.TaskItem)ns.GetItemFromID(taskItem.UserProperties["Parent"].Value.ToString());
                        //получаем текущий испектор таски
                        Outlook.Inspector inspector = theitem.GetInspector;
                        if (inspector != null)
                        {
                            inspector.Display();
                            Marshal.ReleaseComObject(inspector);
                            inspector = null;
                        }
                        Marshal.ReleaseComObject(theitem); theitem = null;
                        Marshal.ReleaseComObject(ns); ns           = null;
                    }
                    else
                    {
                        MessageBox.Show("Parent отсутсвует или удален");
                    }
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show("Parent отсутсвует или удален");
                }
            }
        }
        /// <summary>
        /// Метод - обновляет задачу в Outlook
        /// </summary>
        /// <param name="task">задача Outlook</param>
        /// <param name="issue">задача Redmine</param>
        private void UpdateOneTaskOutlook(TaskItem task, Issue issue)
        {
            Dictionary <string, string> OutlookTasks = GetTasksFromCurrentFolder();

            //To Do чтобы сохраняла в текущий фолдер !!!!!
            task         = (Outlook.TaskItem)CustomFolder.Items.Add(Outlook.OlItemType.olTaskItem);
            task.Subject = issue.Subject;
            Issue parentRedmine           = null;
            bool  flagEistParentInOutlook = false;

            if (issue.ParentIssue != null)
            {
                parentRedmine = manager.GetObject <Issue>(issue.ParentIssue.Id.ToString(), new NameValueCollection());
                foreach (var taskID in OutlookTasks)
                {
                    //если есть такая задача в текущей папке, то просто в свойстве добавляем ее ид
                    if (taskID.Key == parentRedmine.Subject)
                    {
                        outlookTaskParent = taskID.Value;
                        task.UserProperties.Add("Parent", OlUserPropertyType.olText, false, true);
                        task.UserProperties["Parent"].Value = outlookTaskParent;
                        MessageBox.Show($"В задачу ***{task.Subject}*** добавлен родитель ***{parentRedmine.Subject}***");
                        flagEistParentInOutlook = true;
                    }
                }
                //если нет то создаем ее в текущей папке и добавляем ее ид в свойства
                if (!flagEistParentInOutlook)
                {
                    Outlook.TaskItem parentItemOutlook = CreateNewTaskOutlook(parentRedmine);
                    outlookTaskParent = parentItemOutlook.EntryID;
                    task.UserProperties.Add("Parent", OlUserPropertyType.olText, false, true);
                    task.UserProperties["Parent"].Value = outlookTaskParent;
                    task.UserProperties.Add("InCalendar", OlUserPropertyType.olText, false, true);
                    task.UserProperties["InCalendar"].Value = "false";
                    MessageBox.Show($"В задачу ***{task.Subject}*** создан и добавлен ***{parentItemOutlook.Subject}***");
                }
            }
            if (issue.Children != null)
            {
                Issue childrenRedmine = null;
                flagEistParentInOutlook = false;

                childrenRedmine = manager.GetObject <Issue>(issue.Children.ToString(), new NameValueCollection());
                foreach (var taskID in OutlookTasks)
                {
                    //если есть такая задача в текущей папке, то просто в свойстве добавляем ее ид
                    if (taskID.Key == childrenRedmine.Subject)
                    {
                        Outlook.NameSpace ns = Globals.ThisAddIn.Application.Session;


                        Outlook.TaskItem chiledrenOutlook = (Outlook.TaskItem)ns.GetItemFromID(taskID.Value);
                        outlookTaskParent = task.EntryID;
                        chiledrenOutlook.UserProperties.Add("Parent", OlUserPropertyType.olText, false, true);
                        chiledrenOutlook.UserProperties["Parent"].Value = outlookTaskParent;
                        MessageBox.Show($"В задачу ***{chiledrenOutlook.Subject}*** добавлен родитель ***{task.Subject}***");
                        flagEistParentInOutlook = true;
                    }
                }
                //если нет то создаем ее в текущей папке и добавляем ее ид в свойства
                if (!flagEistParentInOutlook)
                {
                    Outlook.TaskItem childernItemOutlook = CreateNewTaskOutlook(childrenRedmine);
                    outlookTaskParent = task.EntryID;
                    childernItemOutlook.UserProperties.Add("Parent", OlUserPropertyType.olText, false, true);
                    childernItemOutlook.UserProperties.Add("InCalendar", OlUserPropertyType.olText, false, true);
                    childernItemOutlook.UserProperties["InCalendar"].Value = "false";
                    childernItemOutlook.UserProperties["Parent"].Value     = outlookTaskParent;
                    MessageBox.Show($"В задачу ***{childernItemOutlook.Subject}*** создан и добавлен ***{task.Subject}***");
                }
            }
            if (issue.DueDate != null)
            {
                task.DueDate = (DateTime)issue.DueDate;
            }
            task.StartDate       = (DateTime)issue.StartDate;
            task.PercentComplete = (int)issue.DoneRatio;
            task.Body            = issue.Description;
            task.ReminderSet     = true;
            task.Save();
        }
Example #16
0
 /// <summary>
 /// Use EntryID for get their objct refernce
 /// </summary>
 /// <param name="EntryID"></param>
 /// <returns></returns>
 public object FindItemfromID(string EntryID)
 {
     return(_NameSpace.GetItemFromID(EntryID));
 }
Example #17
0
        private Outlook.ContactItem NTTranslator(NTContact item)
        {
            Outlook.Application outlookApp      = new Outlook.Application();
            Outlook.NameSpace   oNS             = outlookApp.GetNamespace("MAPI");
            Outlook.MAPIFolder  oContactsFolder = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
            Outlook.ContactItem oItem           = null;

            try
            {
                oItem = (Outlook.ContactItem)oNS.GetItemFromID(item.NTItemId, oContactsFolder.StoreID);
            }
            catch (Exception)
            {
            }
            if (oItem == null)
            {
                oItem = (Outlook.ContactItem)outlookApp.CreateItem(Outlook.OlItemType.olContactItem);
            }

            oItem.User1 = item.NTUsername;

            oItem.Account = item.NTAccountName;
            //item.NTAnniversary = oItem.Anniversary.ToString();
            //item.NTAssistantName = oItem.AssistantName;
            //item.NTAssistantTelephoneNumber = oItem.AssistantTelephoneNumber;
            //item.NTBirthday = oItem.Birthday.ToString();
            //item.NTBody = oItem.Body;
            //item.NTBusiness2TelephoneNumber = oItem.Business2TelephoneNumber;
            //item.NTBusinessAddressCity = oItem.BusinessAddressCity;
            //item.NTBusinessAddressCountry = oItem.BusinessAddressCountry;
            //item.NTBusinessAddressPostalCode = oItem.BusinessAddressPostalCode;
            //item.NTBusinessAddressState = oItem.BusinessAddressState;
            //item.NTBusinessAddressStreet = oItem.BusinessAddressStreet;
            //item.NTBusinessFaxNumber = oItem.BusinessFaxNumber;
            //item.NTBusinessTelephoneNumber = oItem.BusinessTelephoneNumber;
            //item.NTCarTelephoneNumber = oItem.CarTelephoneNumber;
            //item.NTCategories = oItem.Categories;
            //item.NTChildren = oItem.Children;
            //item.NTCompanyName = oItem.CompanyName;
            oItem.CompanyMainTelephoneNumber = item.NTCompanyTelephoneNumber;
            //item.NTCustomerId = oItem.CustomerID;
            //item.NTDepartment = oItem.Department;
            oItem.Email1Address = item.NTEmail1Address;
            //item.NTEmail2Address = oItem.Email2Address;
            //item.NTEmail3Address = oItem.Email3Address;
            //item.NTFileAs = oItem.FileAs;
            oItem.FirstName = item.NTFirstName;
            //item.NTGovernmentId = oItem.GovernmentIDNumber;
            //item.NTHome2TelephoneNumber = oItem.Home2TelephoneNumber;
            oItem.HomeAddressCity       = item.NTHomeAddressCity;
            oItem.HomeAddressCountry    = item.NTHomeAddressCountry;
            oItem.HomeAddressPostalCode = item.NTHomeAddressPostalCode;
            oItem.HomeAddressState      = item.NTHomeAddressState;
            oItem.HomeAddressStreet     = item.NTHomeAddressStreet;
            oItem.HomeFaxNumber         = item.NTHomeFaxNumber;
            oItem.HomeTelephoneNumber   = item.NTHomeTelephoneNumber;
            //item.NTIM2Address = "";
            //item.NTIM3Address = "";
            //oItem.EntryID =item.NTItemId;
            //item.NTJobTitle = oItem.JobTitle;
            oItem.LastName = item.NTLastName;
            //item.NTManager = oItem.ManagerName;
            oItem.MiddleName            = item.NTMiddleName;
            oItem.MobileTelephoneNumber = item.NTMobileTelephoneNumber;
            //Item.NickName = item.NTNickname
            //item.NTOfficeLocation = oItem.OfficeLocation;
            //item.NTOtherAddressCity = oItem.OtherAddressCity;
            //item.NTOtherAddressCountry = oItem.OtherAddressCountry;
            //item.NTOtherAddressPostalCode = oItem.OtherAddressPostalCode;
            //item.NTOtherAddressState = oItem.OtherAddressState;
            //item.NTOtherAddressStreet = oItem.OtherAddressStreet;
            //item.NTPagerNumber = oItem.PagerNumber;
            //item.NTPicture = "";
            //item.NTProperties = "";
            //item.NTRadioTelephoneNumber = oItem.RadioTelephoneNumber;
            //item.NTRingTone = "";
            //item.NTSpouse = oItem.Spouse;
            //item.NTSuffix = oItem.Suffix;
            //item.NTTitle = oItem.Title;
            //item.NTWebPage = oItem.WebPage;
            //item.NTYomiCompanyName = oItem.YomiCompanyName;
            //item.NTYomiFirstName = oItem.YomiFirstName;
            //item.NTYomiLastName = oItem.YomiLastName;
            oItem.IMAddress = item.NTJabberID;

            return(oItem);
        }