Ejemplo n.º 1
2
        private void button1_Click(object sender, RibbonControlEventArgs e)
        {
            Outlook.Application application = new Outlook.Application();
            Outlook.NameSpace ns = application.GetNamespace("MAPI");

            try
            {
                //get selected mail item
                Object selectedObject = application.ActiveExplorer().Selection[1];
                Outlook.MailItem selectedMail = (Outlook.MailItem)selectedObject;

                //create message
                Outlook.MailItem newMail = application.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
                newMail.Recipients.Add(ReadFile());
                newMail.Subject = "SPAM";
                newMail.Attachments.Add(selectedMail, Microsoft.Office.Interop.Outlook.OlAttachmentType.olEmbeddeditem);

                newMail.Send();
                selectedMail.Delete();

                System.Windows.Forms.MessageBox.Show("Spam notification has been sent.");
            }
            catch
            {
                System.Windows.Forms.MessageBox.Show("You must select a message to report.");
            }
        }
Ejemplo n.º 2
0
        public void ForwardEmailUsingOutLook(string witBody, String witName, List<Docs> docs)
        {

            Microsoft.Office.Interop.Outlook.Application outlookApp = new Microsoft.Office.Interop.Outlook.Application();

            if (outlookApp.ActiveExplorer().Selection.Count > 0)
            {
                Object selectedMail = outlookApp.ActiveExplorer().Selection[1];

                if (selectedMail is Microsoft.Office.Interop.Outlook.MailItem)
                {
                    Microsoft.Office.Interop.Outlook.MailItem mail = (selectedMail as Microsoft.Office.Interop.Outlook.MailItem);
                    Microsoft.Office.Interop.Outlook.MailItem forwardMail = mail.Forward();

                    Microsoft.Office.Interop.Outlook.MailItem email =
                    (Microsoft.Office.Interop.Outlook.MailItem)outlookApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

                    email.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatRichText;
                    email.HTMLBody = witBody + forwardMail.HTMLBody;

                    //email.To = mail.SenderEmailAddress;
                    email.Subject = forwardMail.Subject;

                    if (docs != null && docs.Count > 0)
                    {

                        foreach (var doc in docs)
                        {
                            if (doc.docId != null)
                            {
                                email.Attachments.Add(doc.localPath + "" + doc.fileName, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, 100000, Type.Missing);
                            }
                        }
                    }

                    email.Display(true);

                }
            }
        }
Ejemplo n.º 3
0
 static public outlook.MailItem[] MailItems()
 {
     Microsoft.Office.Interop.Outlook.Application app = null;
     app = new Microsoft.Office.Interop.Outlook.Application();
     ArrayList mailItems = new ArrayList();
     foreach (var selection in app.ActiveExplorer().Selection)
     {
         if (selection is outlook.MailItem)
         {
             mailItems.Add((outlook.MailItem)selection);
         }
     }
     return (outlook.MailItem[])mailItems.ToArray(typeof(outlook.MailItem));
 }
Ejemplo n.º 4
0
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            // Initialize variables.
            m_Application = this.Application;
            m_Explorers = m_Application.Explorers;
            m_Inspectors = m_Application.Inspectors;
            m_Windows = new List<OutlookExplorer>();
            m_InspectorWindows = new List<OutlookInspector>();

            // Wire up event handlers to handle multiple Explorer windows.
            m_Explorers.NewExplorer +=
                new Outlook.ExplorersEvents_NewExplorerEventHandler(m_Explorers_NewExplorer);
            // Wire up event handler to handle multiple Inspector windows.
            m_Inspectors.NewInspector +=
                new Outlook.InspectorsEvents_NewInspectorEventHandler(m_Inspectors_NewInspector);
            // Add the ActiveExplorer to m_Windows.
            Outlook.Explorer expl = m_Application.ActiveExplorer()
                as Outlook.Explorer;
            OutlookExplorer window = new OutlookExplorer(expl);
            m_Windows.Add(window);
            // Hook up event handlers for window.
            window.Close += new EventHandler(WrappedWindow_Close);
            window.InvalidateControl += new EventHandler<OutlookExplorer.InvalidateEventArgs>(WrappedWindow_InvalidateControl);

            // Get IPictureDisp for CurrentUser on startup.
            try
            {
                Outlook.AddressEntry addrEntry =
                    Globals.ThisAddIn.Application.Session.CurrentUser.AddressEntry;
                if (addrEntry.Type == "EX")
                {
                    Outlook.ExchangeUser exchUser =
                        addrEntry.GetExchangeUser() as Outlook.ExchangeUser;
                    m_pictdisp = exchUser.GetPicture() as stdole.IPictureDisp;
                }
            }
            catch (Exception ex)
            {
                // Write exception to debug window.
                Debug.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 5
0
        private void ExtractEmail(string country, string fileType, string docType, string countryCode, string exportScheme, string emailType)
        {
            Application application = Globals.ThisAddIn.Application;
            string      userID      = UserPrincipal.Current.ToString();

            if (application.ActiveExplorer().Selection.Count > 0)
            {
                foreach (MailItem item in application.ActiveExplorer().Selection)
                {
                    string folder = this.getOutputFolder(country, docType, item);
                    if (item.Attachments.Count <= 0)
                    {
                        if (MessageBox.Show("Do you really want to send this e-mail to EDMS?", "Sending e-mail without attachments.", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                        {
                            continue;
                        }
                        this.ExtractEmailBody(item, folder, "Message_Body.rtf");
                        this.ConvertFiles(folder, country, fileType, docType, countryCode, item);
                        this.sendDoc2EDMS(docType, countryCode, exportScheme, userID, "exported email.pdf", folder, item);
                        continue;
                    }
                    List <string> list = new List <string>();
                    int           num  = 1;
                    while (true)
                    {
                        if (num > item.Attachments.Count)
                        {
                            SelectAttachments attachments = new SelectAttachments(list);
                            if (attachments.ShowDialog() == DialogResult.OK)
                            {
                                if ((attachments.selectedAttachments.Capacity == 0) && attachments.withMailBody)
                                {
                                    this.ExtractEmailBody(item, folder, "Message_Body.rtf");
                                    this.ConvertFiles(folder, country, fileType, docType, countryCode, item);
                                    this.sendDoc2EDMS(docType, countryCode, exportScheme, userID, "exported email.pdf", folder, item);
                                }
                                else if ((attachments.selectedAttachments.Capacity > 0) && !attachments.withMailBody)
                                {
                                    this.ExtractEmailAttachments(application, item, folder, attachments.selectedAttachments);
                                    this.ConvertFiles(folder, country, fileType, docType, countryCode, item, attachments.selectedAttachments, "e-mail from " + item.SenderName + " " + this.GetSenderSMTPAddress(item));
                                    this.sendDoc2EDMS(docType, countryCode, exportScheme, userID, "exported email.pdf", folder, item);
                                }
                                else if ((attachments.selectedAttachments.Capacity > 0) && attachments.withMailBody)
                                {
                                    this.ExtractEmailBody(item, folder, "Message_Body.rtf");
                                    this.ExtractEmailAttachments(application, item, folder, attachments.selectedAttachments);
                                    this.ConvertFiles(folder, country, fileType, docType, countryCode, item, attachments.selectedAttachments, "e-mail from " + item.SenderName + " " + this.GetSenderSMTPAddress(item));
                                    this.sendDoc2EDMS(docType, countryCode, exportScheme, userID, "exported email.pdf", folder, item);
                                }
                                else if ((attachments.selectedAttachments.Capacity == 0) && !attachments.withMailBody)
                                {
                                    MessageBox.Show("You did not select either attachment or e-mail body. \n\nThere is nothing to be sent. \n\n Please get back and make your choice. ", "Empty selection.", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                                }
                            }
                            break;
                        }
                        if (!item.Attachments[num].FileName.EndsWith(".eml") && !item.Attachments[num].FileName.EndsWith(".msg"))
                        {
                            list.Add(item.Attachments[num].FileName);
                        }
                        else
                        {
                            string path = Path.Combine(@"C:\Users\Public\pdfWork\", item.Attachments[num].FileName);
                            item.Attachments[num].SaveAsFile(path);
                            MailItem attachedEmail = Globals.ThisAddIn.Application.Session.OpenSharedItem(path) as MailItem;
                            list.Add(attachedEmail.Subject.Replace(";", "") + "_Message_Body");

                            //add attachment to list
                            int attachmentsCounter = 0;
                            foreach (System.Net.Mail.Attachment attachment in attachedEmail.Attachments)
                            {
                                attachmentsCounter++;
                                list.Add(attachedEmail.Subject + "_" + attachedEmail.Attachments[attachmentsCounter].FileName);
                            }
                        }
                        num++;
                    }
                }
            }
        }
Ejemplo n.º 6
0
        private void pb_DoWork(object sender, DoWorkEventArgs e)
        {
            EmailFunctions functions = new EmailFunctions(OurDebug, Settings.boxMailName, DateTime.Parse(Settings.raportDate));

            List <MailItem> emails = new List <MailItem>();
            MailItem        email1 = null;
            int             DebugCorrectEmailsCounter = 0;

            functions.choiceOfFileFormat(Settings.checkList);


            //Initialize outlook app
            Outlook.Application oApp    = new Outlook.Application();
            NameSpace           oNS     = oApp.GetNamespace("mapi");
            MAPIFolder          oInbox2 = oApp.ActiveExplorer().CurrentFolder as MAPIFolder;

            OurDebug.AppendInfo("Wybrany folder ", oInbox2.Name);
            Items oItems = oInbox2.Items;

            OurDebug.AppendInfo("Email's amount", oItems.Count.ToString());

            //Sort all items
            oItems.Sort("[ReceivedTime]", true);

            //Debug info for mails
            OurDebug.AppendInfo("\n\n ************************MAILS*******************\n\n");

            //Get only mails from two weeks ago
            DebugForEachCounter = functions.getOnlyEmailsForTwoWeeksAgo(DebugForEachCounter, email1, oItems, DebugCorrectEmailsCounter, emails);

            //Show how many times foreach is performed
            OurDebug.AppendInfo("\n\n", "Ile razy foreach: ", DebugForEachCounter.ToString(), "Maile brane pod uwage po wstepnej selekcji: ", "\n\n");

            //Delete duplicates from email in the same name or the same thread
            try
            {
                emails = functions.emailsWithoutDuplicates(emails);
                emails = functions.removeDuplicateOneMoreTime(emails);
            }
            catch (Exception ex)
            {
                OurDebug.AppendInfo("!!!!!!!!************ERROR***********!!!!!!!!!!\n", "Usuwanie duplikatow nie dziala", ex.StackTrace, "\n", ex.Message);
            }

            int counterForAllEmails = 0;

            //Iterate all emails
            foreach (MailItem newEmail in emails)
            {
                try
                {
                    List <bool> categoryList;
                    //Divide on category
                    if (functions.isMultipleCategoriesAndAnyOfTheireInterestedUs(newEmail.Categories))
                    {
                        //Get inflow date and set to category
                        DateTime friday = functions.getInflowDate();
                        categoryList = functions.selectCorrectEmailType(newEmail);
                        OurData.addNewItem(newEmail.Subject, categoryList);
                    }
                }
                catch (Exception ex)
                {
                    OurDebug.AppendInfo("!!!!!!!!************ERROR***********!!!!!!!!!!\n", "Ribbon1.cs line:96. Problem in ID message.", ex.Message, "\n", ex.StackTrace);
                }
                counterForAllEmails++;
                backgroundWorker1.ReportProgress(counterForAllEmails / emails.Count * 60);
            }
            OurData.lastTuning();
            //Start create excel raport
            if (checkExcel)
            {
                fullInfoBox += "\n\nYour report (Excel) is saved: " + Settings.OutputRaportFileName + ".xlsx";
                ExcelSheet raport = new ExcelSheet();
                raport.SaveExcel(Settings.OutputRaportFileName, OurDebug);
            }
            backgroundWorker1.ReportProgress(80);
            //Save to txt file and word
            if (checkWord)
            {
                fullInfoBox += "\n\nYour report(Word) is saved: " + Settings.OutputRaportFileName + ".docx";
                string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + Settings.OutputRaportFileName + ".docx";
                toBeSavedWord.WriteToWord(path, OurDebug, DateTime.Parse(Settings.raportDate));
            }
            backgroundWorker1.ReportProgress(100);
            Thread.Sleep(1000);


            //Raport is saved
            OurDebug.AppendInfo("Your report is SAVED :D");
        }
Ejemplo n.º 7
0
 private void Form1_Shown(object sender, EventArgs e)
 {
     label1.Text = "Total number of mails in inbox: " + App.ActiveExplorer().CurrentFolder.Items.Count.ToString();
 }
Ejemplo n.º 8
0
        public void GetEmails()
        {
            //MessageBox.Show("In GetEmails");
            Outlook.MAPIFolder inbox          = null;
            Outlook.NameSpace  ns             = null;
            Outlook.Items      items          = null;
            Outlook.MailItem   mailItem       = null;
            string             subjectName    = string.Empty;
            DateTime           lastrunDate    = Convert.ToDateTime(File.ReadLines("log.txt").Last());
            string             subjectFilter  = "[Subject] = 'Cutler / (1) DEFICIT EXECUTIONS'";
            string             subjectFilter2 = "[Subject] = 'STOCK LOAN EXECUTION'";
            string             subjectFilter3 = "[Subject] = 'CUTLER/ (1) DEFICIT EXECUTIONS'";
            List <string>      subjectFilters = new List <string>();

            subjectFilters.Add(subjectFilter);
            subjectFilters.Add(subjectFilter2);
            subjectFilters.Add(subjectFilter3);

            try
            {
                if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
                {
                    //Check if Outlook is open.
                    //MessageBox.Show("Outlook Is Open");
                    Outlook.Application applic = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
                    inbox = applic.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                }
                else
                {
                    //Open Outlook if closed.
                    //MessageBox.Show("Outlook is Closed...Opening an instance of Outlook");
                    Outlook.Application app = new Outlook.Application();
                    ns    = app.GetNamespace("MAPI");
                    inbox = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                    ns    = null;
                }

                foreach (string subject in subjectFilters)
                {
                    object folderItem;
                    items      = inbox.Items;
                    folderItem = items.Find(subject);
                    //MessageBox.Show("Checking for Emails since " + lastrunDate + " with subject " + subject);

                    while (folderItem != null)
                    {
                        mailItem = folderItem as Outlook.MailItem;
                        //Check if email rcvd after last run date.
                        if (mailItem != null && Convert.ToDateTime(mailItem.ReceivedTime) > lastrunDate)
                        {
                            emails.Add(mailItem);
                            subjectName += "\n" + mailItem.Subject + mailItem.SenderEmailAddress + mailItem.SentOn;
                        }
                        folderItem = items.FindNext();
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show("{0} Exception caught.", e.Message);
            }
            finally
            {
                if (items != null)
                {
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(items);
                }
                if (inbox != null)
                {
                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(inbox);
                }
            }
            if (emails.Count == 0)
            {
                MessageBox.Show("No Emails Found");
                Environment.Exit(0);
            }
            else
            {
                MessageBox.Show("Found " + emails.Count + " Emails");
            }
            return;
        }
Ejemplo n.º 9
0
        public int countMail()
        {
            /*

             * Gives the number of selected mail.
             * returns: Number of selected mail.

             */
            cnt_mail = 0;
            Microsoft.Office.Interop.Outlook.Application app = null;

            app = new Microsoft.Office.Interop.Outlook.Application();
            foreach (var selection in app.ActiveExplorer().Selection)
            {
                cnt_mail = app.ActiveExplorer().Selection.Count;
            }

            return cnt_mail;
        }
        public void OnConvertButton(Office.IRibbonControl control)
        {
            StagingTicket ticket = new StagingTicket();

            Outlook.Application application = new Outlook.Application();
            Outlook.NameSpace   ns          = application.GetNamespace("MAPI");

            //get selected outlook object / mail item
            Object selectedObject = application.ActiveExplorer().Selection[1];

            Outlook.MailItem selectedMail = (Outlook.MailItem)selectedObject;

            //in case a email object si selected run the workflow
            if (selectedObject != null)
            {
                //1. invoke web service
                try
                {
                    //instanciate service and invoke it create the ticket and to receive the ticket reference (ID)
                    Remedy2OutlookService service = new Remedy2OutlookService();
                    ticket = service.invoke(selectedMail);
                }
                catch (Exception ex)
                {
                    string path = AppDomain.CurrentDomain.BaseDirectory + @"\temp";
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }

                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(path + @"\errors.log", true))
                    {
                        file.WriteLine(DateTime.Now.ToString() + " - " + ex.Message + "\n" + ex.ToString());
                    }

                    // display an error message
                    MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }


                //2. open submitted ticket in browser or display info/warn/error messages
                if (Properties.Settings.Default.OpenInBrowser && ticket.wid != null)
                {
                    dynamic ie  = Activator.CreateInstance(Type.GetTypeFromProgID("InternetExplorer.Application"));
                    string  url = Properties.Settings.Default.AppConsoleURL;

                    if (url.EndsWith("/"))
                    {
                        url.Remove(url.Length - 1);
                    }
                    if (url.IndexOf("?", 0) > 0)
                    {
                        url += "&eid=" + ticket.wid;
                    }
                    else
                    {
                        url += "?eid=" + ticket.wid;
                    }

                    ie.AddressBar = false;
                    ie.MenuBar    = false;
                    ie.ToolBar    = false;
                    ie.Visible    = true;
                    ie.Navigate2(url);
                }
                else
                {
                    if (ticket.wid != null && String.Equals(ticket.sts, "done"))
                    {
                        MessageBox.Show("Remedy workflow ticket has been created: " + ticket.wid, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else if (ticket.rid != null && String.Equals(ticket.sts, "open"))
                    {
                        MessageBox.Show("Selected email is transferred to Remedy into the staging record [" + ticket.rid + "] but the fulfillment ticket was not created due to an error or misconfiguration.\n\nContact your Administrator!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else if (String.Equals(ticket.sts, "error") && ticket.log != null)
                    {
                        MessageBox.Show("Remedy workflow error: " + ticket.log + ".\n\nContact your Administrator!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }


                //3. mark selected email as read
                if (Properties.Settings.Default.ReadMail && ticket.wid != null)
                {
                    selectedMail.UnRead = false;
                    selectedMail.Save();
                }


                //4. insert reference ticket number in the
                if (Properties.Settings.Default.InsertInSubject && ticket.wid != null)
                {
                    selectedMail.Subject = ticket.wid + ": " + selectedMail.Subject;
                    selectedMail.Save();
                }

                //5. copy selected email item into Backup MAPI folder (if not exist will be created)
                if (Properties.Settings.Default.BackupMail && ticket.wid != null)
                {
                    Outlook.Folder     inbox  = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox) as Outlook.Folder;
                    Outlook.MAPIFolder backup = null;

                    foreach (Outlook.MAPIFolder subfolder in inbox.Folders)
                    {
                        if (String.Equals(subfolder.Name, "Backup"))
                        {
                            backup = subfolder;
                            break;
                        }
                    }

                    if (backup == null)
                    {
                        try
                        {
                            backup = inbox.Folders.Add("Backup", Outlook.OlDefaultFolders.olFolderInbox);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Error trying to create Backup MAPI folder: " + ex.Message + ".\n\nContact your Administrator or create it manually!", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }

                    if (backup != null)
                    {
                        Outlook.MailItem copyMail = selectedMail.Copy();
                        copyMail.Move(backup);
                    }

                    if (inbox != null)
                    {
                        Marshal.ReleaseComObject(inbox);
                    }
                    if (backup != null)
                    {
                        Marshal.ReleaseComObject(backup);
                    }
                }

                //6. delete selected email item
                if (Properties.Settings.Default.RemoveMail && ticket.wid != null)
                {
                    selectedMail.Delete();
                }
            }
        }
        public void removeAttachments_Click(Office.IRibbonControl control)
        {
            int itemCountTotal   = 0;
            int itemCountRemoved = 0;
            int min = 0;

            Outlook.Application application = new Outlook.Application();
            Outlook.Explorer    explorer    = application.ActiveExplorer();
            Outlook.Selection   selected    = explorer.Selection;
            DialogResult        dr_Delete   = MessageBox.Show("Are you sure you want to delete all attachments from the selected items?", "Warning", MessageBoxButtons.YesNo);

            if (dr_Delete == DialogResult.Yes)
            {
                foreach (Object obj in selected)
                {
                    string msg = null;
                    itemCountTotal++;
                    if (obj is Outlook.MailItem)
                    {
                        min = 0;
                        Outlook.MailItem    mailItem    = (Outlook.MailItem)obj;
                        Outlook.Attachments attachments = mailItem.Attachments;
                        // Iterate through attachments of this email
                        if (attachments != null && attachments.Count > 0)
                        {
                            int attachmentCount = attachments.Count;
                            int position        = 1;
                            for (int i = 1; i <= attachmentCount; i++)
                            {
                                Outlook.Attachment attachment = attachments[position];
                                var    flags    = attachment.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x37140003");
                                String fileName = attachments[position].DisplayName;
                                // To ignore embedded attachments
                                if (flags != 4)
                                {
                                    // To ignore embedded attachments in RTF mail with type 6
                                    if ((int)attachment.Type != 6)
                                    {
                                        // Delete attachment and append a message to the body.
                                        attachments[position].Delete();
                                        min  = 1;
                                        msg += fileName + ", ";
                                    }
                                }
                                else
                                {
                                    position++;
                                    flags = attachment.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x37140003");
                                }
                            }
                            if (min == 1)
                            {
                                itemCountRemoved++;
                            }
                        }
                        if (itemCountRemoved >= 1)
                        {
                            msg = msg.Remove(msg.Length - 2);
                            mailItem.HTMLBody = "<p>ATTACHMENTS REMOVED: [" + msg + "]</p>" + mailItem.HTMLBody;
                            mailItem.Save();
                        }
                    }
                }
                if (itemCountRemoved == 0)
                {
                    MessageBox.Show("There are no attachments to remove.");
                }
                else
                {
                    MessageBox.Show("Removed attachments from " + itemCountRemoved + " out of " + itemCountTotal + " emails.");
                }
            }
            else if (dr_Delete == DialogResult.No)
            {
            }
        }
        public void saveAttachments_Click(Office.IRibbonControl control)
        {
            bool   firstPrompt      = false;
            int    itemCountTotal   = 0;
            int    itemCountSaved   = 0;
            int    validAttachments = 0;
            int    min  = 0;
            string path = null;

            Outlook.Application application = new Outlook.Application();
            Outlook.Explorer    explorer    = application.ActiveExplorer();
            Outlook.Selection   selected    = explorer.Selection;
            foreach (Object obj in selected)
            {
                itemCountTotal++;
                if (obj is Outlook.MailItem)
                {
                    min = 0;
                    Outlook.MailItem    mailItem    = (Outlook.MailItem)obj;
                    Outlook.Attachments attachments = mailItem.Attachments;
                    if (attachments != null && attachments.Count > 0)
                    {
                        int attachmentCount = attachments.Count;
                        // Iterate through attachments of this email
                        for (int i = 1; i <= attachmentCount; i++)
                        {
                            Outlook.Attachment attachment = attachments[i];
                            var    flags    = attachment.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x37140003");
                            String fileName = attachments[i].DisplayName;
                            // To ignore embedded attachments
                            if (flags != 4)
                            {
                                // To ignore embedded attachments in RTF mail with type 6
                                if ((int)attachment.Type != 6)
                                {
                                    if (firstPrompt != true)
                                    {
                                        DialogResult result = folderBrowserDialog1.ShowDialog();
                                        if (result == DialogResult.OK)
                                        {
                                            path = folderBrowserDialog1.SelectedPath;
                                        }
                                        else if (result == DialogResult.Cancel)
                                        {
                                            return;
                                        }
                                        firstPrompt = true;
                                    }
                                    validAttachments++;
                                    // If file exists, prompt user to overwrite; otherwise save the file. If user clicks yes, overwrite; user clicks no, do nothing.
                                    if (File.Exists(path + "\\" + fileName))
                                    {
                                        DialogResult dialogResult = MessageBox.Show("A file named \"" + fileName + "\" already exists in this directory. Would you like to save this as an additional copy?", "File exists", MessageBoxButtons.YesNo);
                                        if (dialogResult == DialogResult.Yes)
                                        {
                                            int count = 1;
                                            min = 1;
                                            string fullPath     = path + "\\" + fileName;
                                            string fileNameOnly = Path.GetFileNameWithoutExtension(fullPath);
                                            string extension    = Path.GetExtension(fullPath);
                                            path = Path.GetDirectoryName(fullPath);
                                            string newFullPath = fullPath;
                                            while (File.Exists(newFullPath))
                                            {
                                                string tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
                                                newFullPath = Path.Combine(path, tempFileName + extension);
                                            }
                                            attachments[i].SaveAsFile(newFullPath);
                                        }
                                        else if (dialogResult == DialogResult.No)
                                        {
                                        }
                                    }
                                    else
                                    {
                                        attachments[i].SaveAsFile(path + "\\" + fileName);
                                        min = 1;
                                    }
                                }
                            }
                        }
                        if (min == 1)
                        {
                            itemCountSaved++;
                        }
                    }
                }
            }
            if (validAttachments == 0)
            {
                MessageBox.Show("There are no attachments to save.");
            }
            else
            {
                MessageBox.Show("Saved attachments from " + itemCountSaved + " out of " + itemCountTotal + " emails.");
            }
        }
Ejemplo n.º 13
0
        void get_Selected_mail_items()
        {
            Microsoft.Office.Interop.Outlook.Application myOlApp = new Microsoft.Office.Interop.Outlook.Application();
            Microsoft.Office.Interop.Outlook.Explorer    objView = myOlApp.ActiveExplorer();
            int k = 1;
            int i = 1;

            foreach (Microsoft.Office.Interop.Outlook.MailItem olMail in objView.Selection)
            {
                try { i += 1; } finally { }
            }

            UboundSelectedMailItems    = i - 1;
            Selected_mail_items        = ResizeArray(ref Selected_mail_items, 0, i - 2, 18, 0);
            Selected_mail_items[0, 0]  = "To";
            Selected_mail_items[0, 1]  = "CC";
            Selected_mail_items[0, 2]  = "Reply_Recipient_Names";
            Selected_mail_items[0, 3]  = "Sender_Email_Address";
            Selected_mail_items[0, 4]  = "Sender_Name";
            Selected_mail_items[0, 5]  = "Sent_On_Behalf_Of_Name";
            Selected_mail_items[0, 6]  = "Sender_Email_Type";
            Selected_mail_items[0, 7]  = "Sent";
            Selected_mail_items[0, 8]  = "Size";;
            Selected_mail_items[0, 9]  = "Unread";
            Selected_mail_items[0, 10] = "Creation_Time";
            Selected_mail_items[0, 11] = "Last_Modification_Time";
            Selected_mail_items[0, 12] = "Sent_On";
            Selected_mail_items[0, 13] = "Received_Time";
            Selected_mail_items[0, 14] = "Importance";
            Selected_mail_items[0, 15] = "Received_By_Name";
            Selected_mail_items[0, 16] = "Received_On_Behalf_Of_Name";
            Selected_mail_items[0, 17] = "Subject";
            Selected_mail_items[0, 18] = "Body";
            k = 1;

            foreach (Microsoft.Office.Interop.Outlook.MailItem olMail in objView.Selection)
            {
                try
                {
                    if (olMail.To == null)
                    {
                        Selected_mail_items[k, 0] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 0] = olMail.To.ToString();
                    }
                    if (olMail.CC == null)
                    {
                        Selected_mail_items[k, 1] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 1] = olMail.CC.ToString();
                    }
                    if (olMail.ReplyRecipientNames == null)
                    {
                        Selected_mail_items[k, 2] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 2] = olMail.ReplyRecipientNames.ToString();
                    }
                    if (olMail.SenderEmailAddress == null)
                    {
                        Selected_mail_items[k, 3] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 3] = olMail.SenderEmailAddress.ToString();
                    }
                    if (olMail.SenderName == null)
                    {
                        Selected_mail_items[k, 4] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 4] = olMail.SenderName.ToString();
                    }
                    if (olMail.SentOnBehalfOfName == null)
                    {
                        Selected_mail_items[k, 5] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 5] = olMail.SentOnBehalfOfName.ToString();
                    }
                    if (olMail.SenderEmailType == null)
                    {
                        Selected_mail_items[k, 6] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 6] = olMail.SenderEmailType.ToString();
                    }
                    if (olMail.Sent == null)
                    {
                        Selected_mail_items[k, 7] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 7] = olMail.Sent.ToString();
                    }
                    if (olMail.Size == null)
                    {
                        Selected_mail_items[k, 8] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 8] = olMail.Size.ToString();
                    }
                    if (olMail.UnRead == null)
                    {
                        Selected_mail_items[k, 9] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 9] = olMail.UnRead.ToString();
                    }
                    if (olMail.CreationTime == null)
                    {
                        Selected_mail_items[k, 10] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 10] = olMail.CreationTime.ToString();
                    }
                    if (olMail.LastModificationTime == null)
                    {
                        Selected_mail_items[k, 11] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 11] = olMail.LastModificationTime.ToString();
                    }
                    if (olMail.SentOn == null)
                    {
                        Selected_mail_items[k, 12] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 12] = olMail.SentOn.ToString("yyddmm-hhmmss");
                    }
                    if (olMail.ReceivedTime == null)
                    {
                        Selected_mail_items[k, 13] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 13] = olMail.ReceivedTime.ToString("yyddmm-hhmmss");
                    }
                    if (olMail.Importance == null)
                    {
                        Selected_mail_items[k, 14] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 14] = olMail.Importance.ToString();
                    }
                    if (olMail.ReceivedByName == null)
                    {
                        Selected_mail_items[k, 15] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 15] = olMail.ReceivedByName.ToString();
                    }
                    if (olMail.ReceivedOnBehalfOfName == null)
                    {
                        Selected_mail_items[k, 16] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 16] = olMail.ReceivedOnBehalfOfName.ToString();
                    }
                    if (olMail.Subject == null)
                    {
                        Selected_mail_items[k, 17] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 17] = olMail.Subject.ToString();
                    }
                    if (olMail.Body == null)
                    {
                        Selected_mail_items[k, 18] = "";
                    }
                    else
                    {
                        Selected_mail_items[k, 18] = olMail.Body.ToString();
                    }

                    k += 1;
                }
                finally { }
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Call VBA script from an Outlook application.
        /// </summary>
        /// <param name="processName">Name of the process being executed</param>
        /// <param name="officeAppName">One of the office app names</param>
        /// <param name="filePath">File path with the VBA script to be executed</param>
        /// <param name="macroName">VBA script name with module/procedure name</param>
        /// <param name="showAlerts">Boolean status to show alerts on open application</param>
        /// <param name="visibleApp">Boolean status to show open application</param>
        /// <param name="saveFile">Boolean status to save or not the file</param>
        /// <param name="stw">Stream writer object to output message to stream buffer</param>
        /// <returns>Returned string from VBA Main Function</returns>
        private static string _RunVBAonOutlook(string processName, string officeAppName, string filePath, string macroName, bool showAlerts = false, bool visibleApp = false, bool saveFile = false, StreamWriter stw = null)
        {
            Outlook.Application _otApp = new Outlook.Application();

            if (_otApp == null)
            {
                throw new ApplicationException("Outlook could not be started. Check if Office Outlook is properly installed in your machine/server. If the error persists, contact XPress robot developers and show a printscreen of this log.");
            }
            else
            {
                string message = DateTime.Now + " [INFO] " + officeAppName + " opened successfully!";
                if (stw != null)
                {
                    stw.WriteLine(message + "\n\r");
                }
                Console.WriteLine(message);

                message = DateTime.Now + " [INFO] " + processName + " is running at " + officeAppName + "...";
                if (stw != null)
                {
                    stw.WriteLine(message + "\n\r");
                }
                Console.WriteLine(message);

                Outlook.MailItem _otSI;
                // Start outlook and mailItem
                if (filePath != null)
                {
                    _otSI = _otApp.Session.OpenSharedItem(filePath) as Outlook.MailItem;
                }
                else
                {
                    _otSI = _otApp.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
                }

                if (visibleApp)
                {
                    _otSI.Display();
                }

                string _result = null;
                // Run the macros by supplying the necessary arguments
                // @Read: https://stackoverflow.com/questions/50878070/execute-vba-outlook-macro-from-powershell-or-c-sharp-console-app
                try
                {
                    // TODO: Test this workaround to run macros on outlook
                    Outlook.Explorer  _otExp = _otApp.ActiveExplorer();
                    CommandBar        _otCb  = _otExp.CommandBars.Add(macroName + "Proxy", Temporary: true);
                    CommandBarControl _otBtn = _otCb.Controls.Add(MsoControlType.msoControlButton, 1);
                    _otBtn.OnAction = macroName;
                    _otBtn.Execute();
                    _otCb.Delete();
                    ObjectService.ReleaseObject(_otCb);
                    ObjectService.ReleaseObject(_otExp);
                    _result = " [INFO] " + officeAppName + " script executed. Check manually if it was executed successfully.";
                }
                catch (Exception)
                {
                    _result = "ERROR | Something wrong in the " + officeAppName + " script happened. Contact XPress robot developers and show a printscreen of this log.";
                }


                if (filePath != null)
                {
                    // Clean-up: Close the mail item
                    if (!saveFile)
                    {
                        _otSI.Close(Outlook.OlInspectorClose.olDiscard);
                    }
                    else
                    {
                        _otSI.Close(Outlook.OlInspectorClose.olSave);
                    }
                    ObjectService.ReleaseObject(_otSI);
                }

                // Clean-up: Close the excel application
                _otApp.Quit();
                ObjectService.ReleaseObject(_otApp);

                return(_result);
            }
        }
Ejemplo n.º 15
0
        public void AddAssociation(Element element, string fileFullName, ElementAssociationType type, string text)
        {
            string noteText = String.Empty;
            string shortcutName = String.Empty;
            string folderPath = element.Path;
            string title = string.Empty;

            List<Element> emailAttachmentElementList = new List<Element>();

            if (text != null)
            {
                noteText = text;
                if (noteText.Length > StartProcess.MAX_EXTRACTTEXT_LENGTH)
                {
                    noteText = noteText.Substring(0, StartProcess.MAX_EXTRACTTEXT_LENGTH) + "...";
                }
                title = noteText.Replace("/", "").Replace("\\", "").Replace("*", "").Replace("?", "").Replace("\"", "").Replace("<", "").Replace(">", "").Replace("|", "").Replace(":", "");
                if (title.Length > StartProcess.MAX_EXTRACTNAME_LENGTH)
                    title = title.Substring(0, StartProcess.MAX_EXTRACTNAME_LENGTH);
                while (title.EndsWith("."))
                    title.TrimEnd('.');
            }

            if (type == ElementAssociationType.File)
            {

            }
            else if (type == ElementAssociationType.FileShortcut)
            {
                if (text == null)
                {
                    noteText = noteText = System.IO.Path.GetFileNameWithoutExtension(fileFullName);
                    title = noteText;
                }

                string fs_fileName = title + System.IO.Path.GetExtension(fileFullName);
                shortcutName = ShortcutNameConverter.GenerateShortcutNameFromFileName(fs_fileName, folderPath);
            }
            else if (type == ElementAssociationType.FolderShortcut)
            {
                if (fileFullName.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()))
                {
                    fileFullName = fileFullName.Substring(0, fileFullName.Length - 1);
                }
                noteText = System.IO.Path.GetFileName(fileFullName);

                string fs_fileName = noteText;
                shortcutName = ShortcutNameConverter.GenerateShortcutNameFromFileName(fs_fileName, folderPath);
            }
            else if (type == ElementAssociationType.Web)
            {
                if (text == null)
                {
                    ActiveWindow activeWindow = new ActiveWindow();
                    title = activeWindow.GetActiveWindowText(activeWindow.GetActiveWindowHandle());
                    if(title.Contains(" - Windows Internet Explorer"))
                    {
                        // IE
                        int labelIndex1 = title.LastIndexOf(" - Windows Internet Explorer");
                        if (labelIndex1 != -1)
                        {
                            title = title.Remove(labelIndex1);
                            noteText = title;
                        }
                    }else if(title.Contains(" - Mozilla Firefox"))
                    {
                        // Firefox
                        int labelIndex2 = title.LastIndexOf(" - Mozilla Firefox");
                        if (labelIndex2 != -1)
                        {
                            title = title.Remove(labelIndex2);
                            noteText = title;
                        }
                    }else
                    {
                        noteText = fileFullName;
                        title = string.Empty;
                    }

                    if (noteText.Length > StartProcess.MAX_EXTRACTTEXT_LENGTH)
                    {
                        noteText = noteText.Substring(0, StartProcess.MAX_EXTRACTTEXT_LENGTH) + "...";
                    }
                }
                shortcutName = ShortcutNameConverter.GenerateShortcutNameFromWebTitle(title, folderPath);

            }
            else if (type == ElementAssociationType.Email)
            {
                Outlook.Application outlookApp = new Outlook.Application();
                Outlook.MailItem mailItem = null;
                if (outlookApp.ActiveExplorer().Selection.Count > 0)
                {
                    mailItem = outlookApp.ActiveExplorer().Selection[1] as Outlook.MailItem;

                    if (mailItem == null)
                        return;

                    if (mailItem != null)
                    {
                        Element associatedElement = element;
                        if (element.IsHeading && element.IsCollapsed)
                        {
                            associatedElement = element.ParentElement;
                        }

                        Regex byproduct = new Regex("att[0-9]+[.txt|.c]");

                        foreach (Outlook.Attachment attachment in mailItem.Attachments)
                        {
                            string attachmentFileName = attachment.FileName;

                            if (!byproduct.IsMatch(attachmentFileName.ToLower()))
                            {
                                string fileNameWithoutExt = System.IO.Path.GetFileNameWithoutExtension(attachmentFileName);
                                string fileNameExt = System.IO.Path.GetExtension(attachmentFileName);
                                string copyPath = associatedElement.Path + attachmentFileName;
                                int index = 2;
                                while (FileNameChecker.Exist(copyPath))
                                {
                                    copyPath = associatedElement.Path + fileNameWithoutExt + " (" + index.ToString() + ")" + fileNameExt;
                                    index++;
                                }
                                attachment.SaveAsFile(copyPath);

                                Element attachmentElement = CreateNewElement(ElementType.Note, " --- " + fileNameWithoutExt);
                                attachmentElement.AssociationType = ElementAssociationType.File;
                                attachmentElement.AssociationURI = System.IO.Path.GetFileName(copyPath);
                                attachmentElement.TailImageSource = FileTypeHandler.GetIcon((ElementAssociationType)attachmentElement.AssociationType, copyPath);
                                emailAttachmentElementList.Add(attachmentElement);
                            }
                        }
                    }
                }
                if ((fileFullName == null) && (mailItem != null))
                {
                    noteText = mailItem.Subject;
                    if (noteText.Length > StartProcess.MAX_EXTRACTTEXT_LENGTH)
                    {
                        noteText = noteText.Substring(0, StartProcess.MAX_EXTRACTTEXT_LENGTH) + "...";
                    }
                    fileFullName = mailItem.EntryID;
                    shortcutName = ShortcutNameConverter.GenerateShortcutNameFromEmailSubject(mailItem.Subject, folderPath);
                }
                else
                {
                    shortcutName = ShortcutNameConverter.GenerateShortcutNameFromEmailSubject(title, folderPath);
                }
            }

            switch (element.Type)
            {
                case ElementType.Heading:
                    if (element.IsExpanded)
                    {
                        Element firstElement = CreateNewElement(ElementType.Note, noteText);
                        InsertElement(firstElement, element, 0);
                        AssignAssociationInfo(firstElement, fileFullName, shortcutName, type);
                        currentElement = firstElement;
                    }
                    else
                    {
                        Element newElement = CreateNewElement(ElementType.Note, noteText);
                        InsertElement(newElement, element.ParentElement, element.Position + 1);
                        AssignAssociationInfo(newElement, fileFullName, shortcutName, type);
                        currentElement = newElement;
                    }
                    break;
                case ElementType.Note:
                    if (element.HasAssociation == false)
                    {
                        if (element.NoteText.Trim() == String.Empty)
                        {
                            element.NoteText = noteText;
                        }
                        AssignAssociationInfo(element, fileFullName, shortcutName, type);
                        currentElement = element;
                    }
                    else
                    {
                        Element newElement = CreateNewElement(ElementType.Note, noteText);
                        InsertElement(newElement, element.ParentElement, element.Position + 1);
                        AssignAssociationInfo(newElement, fileFullName, shortcutName, type);
                        currentElement = newElement;
                    }
                    break;
            };

            int curr_index = currentElement.Position;
            foreach (Element emailAttachmentElement in emailAttachmentElementList)
            {
                InsertElement(emailAttachmentElement, currentElement.ParentElement, curr_index);
                curr_index++;
            }
        }
Ejemplo n.º 16
0
        public void getActiveLetter()
        {
            Outlook.Application app = new Outlook.Application();
            Outlook.Selection items = app.ActiveExplorer().Selection;
            foreach(object mail in items) {
                Outlook.MailItem im = (Outlook.MailItem)mail;
                _projectName = im.Subject.Replace(":", "");
                _startDate = im.CreationTime.Date.ToShortDateString();

                Directory.CreateDirectory("temp");
                foreach(Outlook.Attachment attach in im.Attachments) {
                    attach.SaveAsFile(AppDomain.CurrentDomain.BaseDirectory + @"temp\" + attach.FileName);
                    _files.Add(attach.FileName);
                }
                im.SaveAs(AppDomain.CurrentDomain.BaseDirectory + @"temp\" + im.Subject.Replace(":", "") + ".msg");
                _files.Add(im.Subject.Replace(":", "") + ".msg");
            }
        }
Ejemplo n.º 17
0
        private void sendToFreshdesk_Click(object sender, RibbonControlEventArgs e)
        {
            Outlook._Application oApp = new Outlook.Application();
            if (oApp.ActiveExplorer().Selection.Count > 0)
            {
                Object selObject = oApp.ActiveExplorer().Selection[1];

                if (selObject is Outlook.MailItem)
                {
                    Outlook.MailItem mailItem = (selObject as Outlook.MailItem);
                    String from = mailItem.SenderEmailAddress.ToString();
                    String fromName = mailItem.SenderName.ToString();
                    String htmlBody = mailItem.HTMLBody;
                    String Body = mailItem.Body;
                    String subject = mailItem.Subject;
                    Body = Body.Replace("\r\n", "\\n");
                    htmlBody = htmlBody.Replace("\r\n", "");

                    string json = "{\"helpdesk_ticket\": {\"email\":\"" + from + "\",\"name\":\"" + fromName + "\",\"subject\":\"" + subject + "\",\"description\":\"" + Body + "\",\"description_html\":\"" + htmlBody + "\"}}";
                    //string json = "{\"helpdesk_ticket\": {\"email\":\"[email protected]\",\"subject\":\"test\",\"description\":\"confirm whether received\"}}";
                    MessageBox.Show(json);
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://nctas.freshdesk.com/helpdesk/tickets.json");
                    //HttpWebRequest class is used to Make a request to a Uniform Resource Identifier (URI).
                    request.ContentType = "application/json";
                    // Set the ContentType property of the WebRequest.
                    request.Method = "POST";
                    byte[] byteArray = Encoding.UTF8.GetBytes(json);
                    // Set the ContentLength property of the WebRequest.
                    request.ContentLength = byteArray.Length;
                    string authInfo = "APIKEY:X";
                    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
                    request.Headers["Authorization"] = "Basic " + authInfo;

                    //Get the stream that holds request data by calling the GetRequestStream method.
                    Stream dataStream = request.GetRequestStream();
                    // Write the data to the request stream.
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    // Close the Stream object.
                    dataStream.Close();
                    WebResponse response = request.GetResponse();
                    // Get the stream containing content returned by the server.
                    //Send the request to the server by calling GetResponse.
                    dataStream = response.GetResponseStream();
                    // Open the stream using a StreamReader for easy access.
                    StreamReader reader = new StreamReader(dataStream);
                    // Read the content.
                    string Response = reader.ReadToEnd();
                    //return the response
                    Console.Out.WriteLine(Response);

                    //MessageBox.Show(fromName);
                    /*if (mailItem.Attachments.Count > 0)
                    {
                        for (int i = 1; i <= mailItem.Attachments.Count; i++)
                        {
                            MessageBox.Show(mailItem.Attachments[i].FileName.ToString());
                        }
                    }*/
                }
            }
        }
Ejemplo n.º 18
0
        public void OnStartupComplete(ref System.Array custom)
        {
            /*

             * When outlook is opened it loads a Menu if Outlook plugin is installed.
             * OpenERP - > Push, Partner ,Documents, Configuration

             */
            Microsoft.Office.Interop.Outlook.Application app = null;
            try
            {
                app = new Microsoft.Office.Interop.Outlook.Application();
                object omissing = System.Reflection.Missing.Value;
                menuBar = app.ActiveExplorer().CommandBars.ActiveMenuBar;
                ConfigManager config = new ConfigManager();
                config.LoadConfigurationSetting();
                OpenERPOutlookPlugin openerp_outlook = Cache.OpenERPOutlookPlugin;
                OpenERPConnect openerp_connect = openerp_outlook.Connection;
                try
                {
                    if (openerp_connect.URL != null && openerp_connect.DBName != null && openerp_connect.UserId != null && openerp_connect.pswrd != "")
                    {
                        string decodpwd = Tools.DecryptB64Pwd(openerp_connect.pswrd);
                        openerp_connect.Login(openerp_connect.DBName, openerp_connect.UserId, decodpwd);
                    }
                }
                catch(Exception )
                {
                    MessageBox.Show("Unable to connect remote Server ' " + openerp_connect.URL + " '.", "OpenERP Connection",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
                }
                newMenuBar = (office.CommandBarPopup)menuBar.Controls.Add(office.MsoControlType.msoControlPopup, omissing, omissing, omissing, true);
                if (newMenuBar != null)
                {
                    newMenuBar.Caption = "OpenERP";
                    newMenuBar.Tag = "My";

                    btn_open_partner = (office.CommandBarButton)newMenuBar.Controls.Add(office.MsoControlType.msoControlButton, omissing, omissing, 1, true);
                    btn_open_partner.Style = office.MsoButtonStyle.msoButtonIconAndCaption;
                    btn_open_partner.Caption = "Contact";
                    //Face ID will use to show the ICON in the left side of the menu.
                    btn_open_partner.FaceId = 3710;
                    newMenuBar.Visible = true;
                    btn_open_partner.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(this.btn_open_partner_Click);

                    btn_open_document = (office.CommandBarButton)newMenuBar.Controls.Add(office.MsoControlType.msoControlButton, omissing, omissing, 2, true);
                    btn_open_document.Style = office.MsoButtonStyle.msoButtonIconAndCaption;
                    btn_open_document.Caption = "Documents";
                    //Face ID will use to show the ICON in the left side of the menu.
                    btn_open_document.FaceId = 258;
                    newMenuBar.Visible = true;
                    btn_open_document.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(this.btn_open_document_Click);

                    btn_open_configuration_form = (office.CommandBarButton)newMenuBar.Controls.Add(office.MsoControlType.msoControlButton, omissing, omissing, 3, true);
                    btn_open_configuration_form.Style = office.MsoButtonStyle.msoButtonIconAndCaption;
                    btn_open_configuration_form.Caption = "Configuration";
                    //Face ID will use to show the ICON in the left side of the menu.
                    btn_open_configuration_form.FaceId = 5644;
                    newMenuBar.Visible = true;
                    btn_open_configuration_form.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(this.btn_open_configuration_form_Click);

                }

            }
            catch (Exception)
            {
                object oActiveExplorer;
                oActiveExplorer = applicationObject.GetType().InvokeMember("ActiveExplorer", BindingFlags.GetProperty, null, applicationObject, null);
                oCommandBars = (office.CommandBars)oActiveExplorer.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, oActiveExplorer, null);
            }
        }
Ejemplo n.º 19
0
        public void OnStartupComplete(ref System.Array custom)
        {
            /*
             *
             * When outlook is opened it loads a Menu if Outlook plugin is installed.
             * OpenERP - > Push, Partner ,Documents, Configuration
             *
             */
            Microsoft.Office.Interop.Outlook.Application app = null;
            try
            {
                app = new Microsoft.Office.Interop.Outlook.Application();
                object omissing = System.Reflection.Missing.Value;
                menuBar = app.ActiveExplorer().CommandBars.ActiveMenuBar;
                ConfigManager config = new ConfigManager();
                config.LoadConfigurationSetting();
                OpenERPOutlookPlugin openerp_outlook = Cache.OpenERPOutlookPlugin;
                OpenERPConnect       openerp_connect = openerp_outlook.Connection;
                try
                {
                    if (openerp_connect.URL != null && openerp_connect.DBName != null && openerp_connect.UserId != null && openerp_connect.pswrd != "")
                    {
                        string decodpwd = Tools.DecryptB64Pwd(openerp_connect.pswrd);
                        openerp_connect.Login(openerp_connect.DBName, openerp_connect.UserId, decodpwd);
                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("Unable to connect remote Server ' " + openerp_connect.URL + " '.", "OpenERP Connection", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
                newMenuBar = (office.CommandBarPopup)menuBar.Controls.Add(office.MsoControlType.msoControlPopup, omissing, omissing, omissing, true);
                if (newMenuBar != null)
                {
                    newMenuBar.Caption = "OpenERP";
                    newMenuBar.Tag     = "My";

                    btn_open_partner         = (office.CommandBarButton)newMenuBar.Controls.Add(office.MsoControlType.msoControlButton, omissing, omissing, 1, true);
                    btn_open_partner.Style   = office.MsoButtonStyle.msoButtonIconAndCaption;
                    btn_open_partner.Caption = "Contact";
                    //Face ID will use to show the ICON in the left side of the menu.
                    btn_open_partner.FaceId = 3710;
                    newMenuBar.Visible      = true;
                    btn_open_partner.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(this.btn_open_partner_Click);

                    btn_open_document         = (office.CommandBarButton)newMenuBar.Controls.Add(office.MsoControlType.msoControlButton, omissing, omissing, 2, true);
                    btn_open_document.Style   = office.MsoButtonStyle.msoButtonIconAndCaption;
                    btn_open_document.Caption = "Documents";
                    //Face ID will use to show the ICON in the left side of the menu.
                    btn_open_document.FaceId = 258;
                    newMenuBar.Visible       = true;
                    btn_open_document.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(this.btn_open_document_Click);

                    btn_open_configuration_form         = (office.CommandBarButton)newMenuBar.Controls.Add(office.MsoControlType.msoControlButton, omissing, omissing, 3, true);
                    btn_open_configuration_form.Style   = office.MsoButtonStyle.msoButtonIconAndCaption;
                    btn_open_configuration_form.Caption = "Configuration";
                    //Face ID will use to show the ICON in the left side of the menu.
                    btn_open_configuration_form.FaceId = 5644;
                    newMenuBar.Visible = true;
                    btn_open_configuration_form.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(this.btn_open_configuration_form_Click);
                }
            }
            catch (Exception)
            {
                object oActiveExplorer;
                oActiveExplorer = applicationObject.GetType().InvokeMember("ActiveExplorer", BindingFlags.GetProperty, null, applicationObject, null);
                oCommandBars    = (office.CommandBars)oActiveExplorer.GetType().InvokeMember("CommandBars", BindingFlags.GetProperty, null, oActiveExplorer, null);
            }
        }