예제 #1
0
        public bool AtualizarMailItem(string categories, string entryId)
        {
            bool ret = false;

            try
            {
                Outlook.Application myApp         = new Outlook.Application();
                Outlook._NameSpace  mapiNameSpace = myApp.GetNamespace("MAPI");

                Outlook.MAPIFolder fd = mapiNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);

                string storeId = fd.StoreID;

                Outlook.MailItem mailItem = mapiNameSpace.GetItemFromID(entryId, storeId) as Outlook.MailItem;

                mailItem.Categories = categories;
                mailItem.Close(Outlook.OlInspectorClose.olSave);

                myApp.Quit();

                ret = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(ret);
        }
예제 #2
0
파일: Form1.cs 프로젝트: Nomanghous/DBtoOL
        // dispose
        public void DisposeExcelInstance()
        {
            if (connection.State == ConnectionState.Open)
            {
                connection.Dispose();
            }

            if (OutLookApp != null)
            {
                try
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(OutLookApp);
                    OutLookApp.Quit();
                }
                catch (Exception ex)
                { }
                finally
                {
                    OutLookApp = null;
                }
            }
            if (Folder_Contacts != null)
            {
                try{
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(Folder_Contacts);
                }
                catch (Exception ex)
                { }
                finally
                {
                    Folder_Contacts = null;
                }
            }
            GC.Collect();
        }
예제 #3
0
        private void MailButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Outlook.Application _app = new Outlook.Application();
                Outlook.MailItem    mail = (Outlook.MailItem)_app.CreateItem(Outlook.OlItemType.olMailItem);

                string filepath = @"D:\Documents\EMPLOYEE PERFORMANCE REVIEW.docx";

                mail.To         = "*****@*****.**";
                mail.Subject    = "Performance Reviews";
                mail.Body       = "benefit enrollments test";
                mail.Importance = Outlook.OlImportance.olImportanceNormal;
                Outlook.Attachment file = mail.Attachments.Add(filepath, Outlook.OlAttachmentType.olByValue, 1, filepath);

                mail.Send();
                MessageBox.Show("message sent");

                _app.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(_app);
            }
            catch
            {
                MessageBox.Show("failed to send email");
            }
        }
예제 #4
0
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            object ae = myApp.ActiveExplorer();
            object ai = myApp.ActiveInspector();
            object aw = myApp.ActiveInspector();

            if (ae == null)
            {
                myApp.Quit();
            }
        }
 public static void Exit()
 {
     if (null != m_Application)
     {
         m_NameSpace = null;
         if (newOutlookInstance)
         {
             m_Application.Quit();
         }
         m_Application = null;
     }
 }
예제 #6
0
 static void Main(string[] args)
 {
     Console.WriteLine("Hit enter key to start.");
     while (Console.ReadKey().Key != ConsoleKey.Enter)
     {
     }
     outlook = new Outlook.Application();
     Outlook.NameSpace nameSpace = outlook.GetNamespace("MAPI");
     try {
         nameSpace.Logon("", "", Missing.Value, Missing.Value);
         for (int i = 1; i <= totalMailCount; i++)
         {
             Outlook.MailItem mail = CreateMail(i, null, recipients[i % recipients.Length]);
             int mod = totalMailCount / attachmentCount;
             if (mod > 0 && i % mod == 0)
             {
                 mail.Attachments.Add(attachmentPath, Outlook.OlAttachmentType.olByValue, 1, attachmentPath);
             }
             mail.Send();
             if (i % progressMessageInterval == 0)
             {
                 Console.WriteLine(string.Format("{0} messages queued in outbox.", i));
             }
         }
     } catch (Exception ex) {
         Console.WriteLine(ex.Message);
         if (ex.InnerException != null)
         {
             Console.WriteLine(ex.InnerException.Message);
         }
         Console.WriteLine(ex.StackTrace);
     } finally {
         Console.WriteLine("Queuing finished.");
         Outlook.Folder outbox = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderOutbox) as Outlook.Folder;
         while (true)
         {
             int itemCount = outbox.Items.Count;
             if (itemCount == 0)
             {
                 break;
             }
             Console.WriteLine("{0} messages left in outbox. Wait until all messages flushed from outbox.", itemCount);
             Thread.Sleep(10000);
         }
         Console.WriteLine("All messages has been sent.");
         Console.WriteLine("Hit enter key to quit.");
         while (Console.ReadKey().Key != ConsoleKey.Enter)
         {
         }
         nameSpace.Logoff();
         outlook.Quit();
     }
 }
        public void Dispose()
        {
            if (m_session != null && m_removeStore && m_rootFolder != null)
            {
                m_session.RemoveStore(m_rootFolder);
            }

            m_session = null;

            m_application?.Quit();
            m_application = null;
        }
예제 #8
0
        public void Quit(bool closeWindows)
        {
            if (closeWindows)
            {
                List <Form> openForms = new List <Form>();
                foreach (Form f in Application.OpenForms)
                {
                    openForms.Add(f);
                }

                foreach (Form f in openForms)
                {
                    f.Close();
                }
            }

            _app.Quit();
        }
예제 #9
0
        public static bool OutlookConverter(string srcfile)
        {
            try
            {
                var format  = Outlook.OlSaveAsType.olHTML;
                var desfile = srcfile.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries)[0] + ".html";

                var outlook          = new Outlook.Application();
                Outlook.MailItem opf = outlook.Session.OpenSharedItem(srcfile);
                opf.SaveAs(desfile, format);
                opf.Close(Outlook.OlInspectorClose.olDiscard);
                outlook.Quit();

                Marshal.ReleaseComObject(opf);
                Marshal.ReleaseComObject(outlook);

                if (opf != null)
                {
                    ReleaseRCM(opf);
                }
                if (outlook != null)
                {
                    ReleaseRCM(outlook);
                }

                opf     = null;
                outlook = null;

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            catch (Exception ex)
            {
                //System.Windows.MessageBox.Show(ex.ToString());
                return(false);
            }
            return(true);
        }
예제 #10
0
        // Usage:
        // using Outlook = Microsoft.Office.Interop.Outlook;
        // Action<Outlook.Application> f = o =>
        // {
        //     var mapif = o.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
        // };
        // Outlook1.With(f);
        static void With(Action <Outlook.Application> f)
        {
            Outlook.Application app = null;

            try
            {
                app = new Outlook.Application();
                f(app);
            }
            finally
            {
                if (app != null)
                {
                    app.Quit();

                    // Both of the following are needed in some cases,
                    // while none of thme are needed in other cases.
                    Marshal.FinalReleaseComObject(app);
                    GC.Collect();
                }
            }
        }
예제 #11
0
        // Usage:
        // using Outlook = Microsoft.Office.Interop.Outlook;
        // Action<Outlook.Application> f = o =>
        // {
        //     var mapif = o.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
        // };
        // Outlook1.With(f);
        internal static void With(Action<Outlook.Application> f)
        {
            Outlook.Application app = null;

            try
            {
                app = new Outlook.Application();
                f(app);
            }
            finally
            {
                if (app != null)
                {
                    app.Quit();

                    // Both of the following are needed in some cases,
                    // while none of thme are needed in other cases.
                    Marshal.FinalReleaseComObject(app);
                    GC.Collect();
                }
            }
        }
예제 #12
0
                /// <summary>
                /// Завершить работу клиента обработки сообщений электронной почты
                /// </summary>
                private void closeOutlook()
                {
                    if (Equals(m_outlookApp, null) == false)
                    {
                        // проверить: не выполнялся ли ранее клиент
                        if (_bIsOutlookRunning == false)
                        {
                            m_outlookApp.Quit();
                        }
                        else
                        {
                            ;
                        }

                        Marshal.ReleaseComObject(m_outlookApp);
                    }
                    else
                    {
                        ;
                    }

                    GC.Collect();
                }
예제 #13
0
        public void Quit()
        {
            if (appInstance != null)
            {
                appInstance.Session.SendAndReceive(false);

                //if outlook was not already running
                if (!outlookAlreadyRunning && exitOutlookOnQuit)
                {
                    for (int i = 0; i < alreadyOpenedCalendars.Count; i++)
                    {
                        alreadyOpenedCalendars[i].Free();
                    }

                    appInstance.Quit();
                    appInstance = null;

                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
            }
        }
예제 #14
0
        private void ScanButton_Click(object sender, RoutedEventArgs e)
        {
            #region Validation

            if (!IsValidEmail(EmailAddressTextBox.Text))
            {
                Log.Log("No valid email address entered.");
                EmailAddressTextBox.Background = System.Windows.Media.Brushes.Red;
                return;
            }
            if (String.IsNullOrWhiteSpace(SourceFolderTextBox.Text))
            {
                Log.Log("No source folder name entered.");
                SourceFolderTextBox.Background = System.Windows.Media.Brushes.Red;
                return;
            }
            if (String.IsNullOrWhiteSpace(DestFolderTextBox.Text))
            {
                Log.Log("No destination folder name entered.");
                DestFolderTextBox.Background = System.Windows.Media.Brushes.Red;
                return;
            }

            #endregion

            try
            {
                List <string> icList = new List <string>();

                #region Outlook

                Outlook.Application     oApp                  = null;
                Outlook.NameSpace       oNameSpace            = null;
                Outlook.MAPIFolder      contractsSourceFolder = null;
                Outlook.MAPIFolder      contractsDestFolder   = null;
                Outlook.Items           items                 = null;
                List <Outlook.MailItem> messages              = null;

                try
                {
                    oApp       = new Outlook.Application();
                    oNameSpace = oApp.GetNamespace("mapi");
                    oNameSpace.Logon(Missing.Value, Missing.Value, false, true);

                    contractsSourceFolder = oNameSpace.Folders[EmailAddressTextBox.Text].Folders[SourceFolderTextBox.Text];
                    contractsDestFolder   = oNameSpace.Folders[EmailAddressTextBox.Text].Folders[DestFolderTextBox.Text];
                    items    = contractsSourceFolder.Items;
                    messages = new List <Outlook.MailItem>();

                    try
                    {
                        foreach (Outlook.MailItem msg in items)
                        {
                            if (msg.SenderName.Contains("DocuSign")) // DocuSign is an older format that isn't used anymore. just skip them
                            {
                                Log.Log("Encountered DocuSign.");
                                continue;
                            }
                            try
                            {
                                string importantContent = "";
                                if (msg.SenderName == "HelloSign")
                                {
                                    if (msg.Subject.Contains("You've been copied on Zojak"))
                                    {
                                        importantContent = msg.Body.Substring(msg.Body.IndexOf("@zojakworldwide.com") + 31);
                                        //importantContent = importantContent.Substring(0, importantContent.IndexOf("@zojakworldwide.com"));
                                        importantContent = importantContent.Substring(0, importantContent.IndexOf("\r\n"));
                                    }
                                    else if (msg.Subject.Contains("has been signed by"))
                                    {
                                        importantContent = msg.Body.Substring(msg.Body.IndexOf("Signer") + 11);
                                        //importantContent = importantContent.Substring(0, importantContent.IndexOf("@zojakworldwide.com"));
                                        importantContent = importantContent.Substring(0, importantContent.IndexOf("\r\n"));
                                    }
                                    else if (msg.Subject.Contains("Everyone has signed"))
                                    {
                                        importantContent = msg.Body.Substring(msg.Body.IndexOf("Signers") + 12);
                                        //importantContent = importantContent.Substring(0, importantContent.IndexOf("@zojakworldwide.com"));
                                        importantContent = importantContent.Substring(0, importantContent.IndexOf("\r\n"));
                                    }
                                }
                                else if (msg.Body.Contains("The document is being sent to:"))
                                {
                                    importantContent = msg.Body.Substring(msg.Body.IndexOf("The document is being sent to:") + 35);
                                    importantContent = importantContent.Substring(0, importantContent.IndexOf("@zojakworldwide.com"));
                                    importantContent = importantContent.Substring(0, importantContent.IndexOf("\r\n"));
                                }
                                else if (msg.Body.Contains("The document is being sent in this order:"))
                                {
                                    importantContent = msg.Body.Substring(msg.Body.IndexOf("1. ") + 3);
                                    //importantContent = importantContent.Substring(0, importantContent.IndexOf("@zojakworldwide.com"));
                                    importantContent = importantContent.Substring(0, importantContent.IndexOf("\r\n"));
                                }
                                else
                                {
                                    Log.Log("Encountered unknown email format.\n\tFrom: " + msg.SenderName + "\n\tSubject: " + msg.Subject + "\n\tReceived at: " + msg.ReceivedTime);
                                    continue;
                                }

                                importantContent = importantContent.Trim(' ', '\r', '\n');
                                icList.Add(importantContent);
                                messages.Add(msg);
                            }
                            catch (Exception ex)
                            {
                                Log.Error(ex, "Error reading message.");
                            }
                        }

                        Log.Log("Completed scan. Found " + icList.Count + " contracts.");
                        Log.Log("Checked for duplicates. Found " + icList.Distinct().ToList().Count + " unique contracts.");
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex, "Error walking through MailItems.");
                        return;
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Error Setting up or leaving Outlook.");
                    return;
                }

                #endregion

                #region Excel

                Excel.Application eApp      = null;
                Excel.Workbook    workbook  = null;
                Excel.Worksheet   worksheet = null;

                try
                {
                    eApp      = new Excel.Application();
                    workbook  = eApp.Workbooks.Add();
                    worksheet = workbook.ActiveSheet;

                    int i = 1;
                    foreach (string contract in icList.Distinct().ToList())
                    {
                        string tempcontract = contract.Trim(')');

                        string email = "";
                        foreach (char letter in contract.Substring(0, contract.Length - 1).Reverse())
                        {
                            tempcontract = tempcontract.Remove(tempcontract.Length - 1);
                            if (letter == '(')
                            {
                                break;
                            }
                            email = email.Insert(0, letter.ToString());
                        }
                        worksheet.Cells[i, 7] = email;

                        if (tempcontract.Contains("("))
                        {
                            tempcontract = tempcontract.Trim(')', ' ');

                            // label
                            string name = "";
                            foreach (char letter in tempcontract.Reverse())
                            {
                                tempcontract = tempcontract.Remove(tempcontract.Length - 1);
                                if (letter == '(')
                                {
                                    break;
                                }
                                name = name.Insert(0, letter.ToString());
                            }
                            worksheet.Cells[i, 1] = name.Trim(' ');

                            // legal
                            worksheet.Cells[i, 4] = tempcontract.Trim(' ');
                        }
                        else if (tempcontract.Contains("/"))
                        {
                            tempcontract = tempcontract.Trim(')', ' ');

                            // label
                            string name = "";
                            foreach (char letter in tempcontract.Reverse())
                            {
                                tempcontract = tempcontract.Remove(tempcontract.Length - 1);
                                if (letter == '/')
                                {
                                    break;
                                }
                                name = name.Insert(0, letter.ToString());
                            }
                            worksheet.Cells[i, 1] = name.Trim(' ');

                            // legal
                            worksheet.Cells[i, 4] = tempcontract.Trim(' ');
                        }
                        else
                        {
                            worksheet.Cells[i, 4] = contract.Substring(0, contract.IndexOf("(")).Trim(' ');
                            worksheet.Cells[i, 1] = contract.Substring(0, contract.IndexOf("(")).Trim(' ');
                        }
                        i++;
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Error Setting up or leaving Excel.");
                    return;
                }

                eApp.Visible = true;

                #endregion
#if !DEBUG
                #region Move emails

                foreach (Outlook.MailItem msg in messages)
                {
                    msg.Move(contractsDestFolder);
                    msg.UnRead = false;
                }

                #endregion
#endif
                #region Global

                // Release Outlook
                try
                {
                    oNameSpace.Logoff();
                    oApp.Quit();

                    messages              = null;
                    items                 = null;
                    contractsDestFolder   = null;
                    contractsSourceFolder = null;
                    oNameSpace            = null;
                    oApp = null;
                }
                catch
                {
                }

                // Release Excel
                try
                {
                    eApp.Quit();

                    worksheet = null;
                    workbook  = null;
                    eApp      = null;
                }
                catch
                {
                }

                Settings.Default.EmailAddress = EmailAddressTextBox.Text;
                Settings.Default.SourceFolder = SourceFolderTextBox.Text;
                Settings.Default.DestFolder   = DestFolderTextBox.Text;
                Settings.Default.Save();

                #endregion
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error thrown to higher level to avoid crashing.");
            }
        }
예제 #15
0
 private void sendEmail(EmailObject eml, bool errEmail = false)
 {
     string myDate = DateTime.Today.ToString("MMMM dd, yyyy");
     Outlook._Application _app = new Outlook.Application();
     Outlook._NameSpace _ns = _app.GetNamespace("MAPI");
     System.Threading.Thread.Sleep(5000); //wait for app to start
     Outlook.MailItem _mail = (Outlook.MailItem)_app.CreateItem(Outlook.OlItemType.olMailItem);
     try
     {
         int fileCount = 0;
         if (qryNames != null)
         {
             foreach (var qryName in qryNames)
             {
                 if (System.IO.File.Exists(AttachmentLocation + qryName))
                 {
                     _mail.Attachments.Add(AttachmentLocation + qryName);
                     fileCount++;
                 }
             }
         }
         _mail.Subject = myDate + " " + eml.Subject;
         _mail.To = eml.To;
         _mail.CC = eml.CC;
         _mail.Body = eml.Body;
         _mail.Importance = Outlook.OlImportance.olImportanceNormal;
         System.Threading.Thread.Sleep(5000); //wait for application to catch up with mail object
         ((Outlook.MailItem)_mail).Send();
         _ns.SendAndReceive(true); //send and receive
         _mail.Close(Outlook.OlInspectorClose.olDiscard);
         System.Threading.Thread.Sleep(5000); //wait for application to catch up with mail object
         _app.Quit();
         isSuccessful = true;
     }
     catch (COMException cEx)
     {
         if (cEx.Message != "The item has been moved or deleted.")
         {
             ErrorHandler.Handle(cEx);
             isSuccessful = false;
         }
     }
     catch (Exception x)
     {
         ErrorHandler.Handle(x);
         isSuccessful = false;
     }
 }
예제 #16
0
 public void CloseOutlook()
 {
     outlook.Quit();
     outlook = null;
 }
예제 #17
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);
            }
        }