Example #1
0
        private void ForwardBtn_Click(object sender, RibbonControlEventArgs e)
        {
            Outlook.MailItem email = ThisEmail();
            email.Save();
            XLMain.Client client = XLMain.Client.FetchClient(XLOutlook.ReadParameter("CrmID", email));
            XLMain.Staff  writer = XLMain.Staff.StaffFromUser(Environment.UserName);
            if (XLantRibbon.staff.Count == 0)
            {
                XLantRibbon.staff = XLMain.Staff.AllStaff();
            }
            StaffSelectForm myForm = new StaffSelectForm(client, writer, XLantRibbon.staff);

            myForm.ShowDialog();
            XLMain.EntityCouplet staff = myForm.selectedStaff;

            string commandfileloc = "";

            string fileId = XLOutlook.ReadParameter("VCFileID", email);

            commandfileloc = XLVirtualCabinet.Reindex(fileId, staff.name, docDate: DateTime.Now.ToString("dd/MM/yyyy"));

            XLVirtualCabinet.BondResult result = XLVirtualCabinet.LaunchCabi(commandfileloc, true);
            if (result.ExitCode != 0)
            {
                MessageBox.Show("Reindex failed please complete manually.");
            }
            else
            {
                // Close the email in Outlook to prevent further changes that won't be saved to VC
                email.Close(Microsoft.Office.Interop.Outlook.OlInspectorClose.olSave);
                // Delete the email from the Drafts folder in Outlook
                email.Delete();
            }
        }
        public void DeleteMessageInDeletedItemFolder()
        {
            // Create a simple mail
            Outlook.MailItem omail = Utilities.CreateSimpleEmail("DeleteMessage");

            // Send mail
            Utilities.SendEmail(omail);

            // Get the latest send mail from send mail folder
            Outlook.MailItem omailSend = Utilities.GetNewestItemInMAPIFolder(sentMailFolder, "DeleteMessage");

            // Delete this mail in send mail folder
            omailSend.Delete();

            // Get the deleted mail in Deleted folder
            Outlook.MailItem odeleteIItem = Utilities.GetNewestItemInMAPIFolder(deletedItemsFolders, "DeleteMessage");

            // Delete it
            odeleteIItem.Delete();

            // Parse the saved trace using MAPI Inspector
            List <string> allRopLists = new List <string>();
            bool          result      = MessageParser.ParseMessage(out allRopLists);

            // Update the XML file for the covered message
            Utilities.UpdateXMLFile(allRopLists);

            // Assert failed if the parsed result has error
            Assert.IsTrue(result, "Case failed, check the details information in error.txt file.");
        }
Example #3
0
        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.");
            }
        }
 /// <summary>
 /// Allows to delete the selected task
 /// </summary>
 /// <param name="sender">Sender</param>
 /// <param name="e">EventArgs</param>
 private void mnuItemDeleteTask_Click(object sender, EventArgs e)
 {
     if (this.lstTasks.SelectedIndices.Count != 0)
     {
         OLTaskItem task = this.lstTasks.SelectedItems[0].Tag as OLTaskItem;
         if (task != null)
         {
             if (MessageBox.Show("Are you sure you want to delete this task?", "Delete task", MessageBoxButtons.YesNo) == DialogResult.Yes)
             {
                 if (task.OriginalItem is Outlook.MailItem)
                 {
                     Outlook.MailItem mail = task.OriginalItem as Outlook.MailItem;
                     mail.Delete();
                 }
                 else if (task.OriginalItem is Outlook.ContactItem)
                 {
                     Outlook.ContactItem contact = task.OriginalItem as Outlook.ContactItem;
                     contact.Delete();
                 }
                 else if (task.OriginalItem is Outlook.TaskItem)
                 {
                     Outlook.TaskItem t = task.OriginalItem as Outlook.TaskItem;
                     t.Delete();
                 }
                 else
                 {
                     // Do nothing
                 }
             }
             // At the end, synchronously "refresh" tasks in case they have changed
             this.RetrieveTasks();
         }
     }
 }
Example #5
0
        private void BtnClearInvitation_Click(object sender, Microsoft.Office.Tools.Ribbon.RibbonControlEventArgs e)
        {
            Func<string, bool> f = s => s.StartsWith("Accepted: ") || s.StartsWith("Declined: ") || s.StartsWith("Tentatively Accepted: ");

            InvitationsCounter = 0;

            Outlook.MAPIFolder inbox = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
            for (int i = inbox.Items.Count; i > 0; i--)
            //foreach (var item in inbox.Items)
            {
                var item = inbox.Items[i];
                Outlook.MailItem mail = item as Outlook.MailItem;
                if (mail != null && mail.Subject != null)
                {
                    //todo: move it to configuration
                    if (f(mail.Subject))
                    {
                        mail.Delete();
                        InvitationsCounter++;
                    }
                }
                Outlook.MeetingItem meeting = item as Outlook.MeetingItem;
                if (meeting != null)
                {
                    if (f(meeting.ConversationTopic))
                    {
                        meeting.Delete();
                        InvitationsCounter++;
                    }
                }
            }
        }
 public void MoveAttactment(Microsoft.Office.Interop.Outlook.MailItem item)
 {
     Microsoft.Office.Interop.Outlook.MailItem   movemail             = null;
     Microsoft.Office.Interop.Outlook.MAPIFolder MaliciousAttachments = destFolder;
     movemail = item;
     if (movemail != null)
     {
         movemail.Move(MaliciousAttachments);
         item.Delete();
     }
 }
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            // Create Application class and get namespace
            Outlook.Application outlook = new Outlook.Application();
            Outlook.NameSpace   ns      = outlook.GetNamespace("Mapi");

            object _missing = Type.Missing;

            ns.Logon(_missing, _missing, false, true);

            // Get Inbox information in objec of type MAPIFolder
            Outlook.MAPIFolder inbox = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);

            Outlook.MailItem item = inbox.Items[0];
            item.Delete();
        }
Example #8
0
        public void MoveMailToSameMailboxFolder()
        {
            // Create a simple mail and save
            Outlook.MailItem omail = Utilities.CreateSimpleEmail("ImportMessageMove");
            omail.Save();
            bool unread = omail.UnRead;

            Thread.Sleep(20000);
            omail.UnRead = !unread;
            Thread.Sleep(20000);
            omail.Save();
            Thread.Sleep(20000);

            // Add a sub-folder named testFolder under the draftsFolders
            Outlook.MAPIFolder testFolder = Utilities.AddSubFolder(draftsFolders, "testFolder");

            // Move mails in draftsFolder to testFolder
            omail.Move(testFolder);

            // Get the latest mail from testFolder folder
            Outlook.MailItem omailInTestFolder = Utilities.GetNewestItemInMAPIFolder(testFolder, "ImportMessageMove");
            omailInTestFolder.Delete();
            int count = 0;

            while (testFolder.Items.Count != 0)
            {
                Thread.Sleep(TestBase.waittimeItem);
                count += TestBase.waittimeItem;
                if (count >= TestBase.waittimeWindow)
                {
                    break;
                }
            }

            // Delete all sub-folders in draftsFolder
            Utilities.RemoveAllSubFolders(TestBase.draftsFolders, true);

            // Parse the saved trace using MAPI Inspector
            List <string> allRopLists = new List <string>();
            bool          result      = MessageParser.ParseMessage(out allRopLists);

            // Update the XML file for the covered message
            Utilities.UpdateXMLFile(allRopLists);

            // Assert failed if the parsed result has error
            Assert.IsTrue(result, "Case failed, check the details information in error.txt file.");
        }
        // For each message in the Lottie folder, check to see if it's part of the same conversation as the message that
        // just arrived.  If so, remove the nag.  Hooray!
        // Limitations:  Don't Lottie more than one e-mail in a conversation.
        private void CheckLottie(object stateInfo)
        {
            // TODO if this is a calendar item, obviously the cast fails.  oops.
            Outlook.MailItem msg = (Outlook.MailItem)stateInfo;
            // remove corresponding timer
            Threading.Timer myTimer;
            String          check = msg.ConversationID;

            if (messagesAndTimers.TryGetValue(msg.ConversationID, out myTimer))
            {
                // right conversation. Check to see if we >shouldn't< cancel the nag.

                if (msg.UserProperties[LottieNoCancelProperty] != null)
                {
                    String inString = msg.UserProperties[LottieNoCancelProperty].Value;
                    if (inString.Equals("True"))
                    {
                        return;
                    }
                }

                // Hooray!  Don't Nag!
                myTimer.Dispose();
                DebugBox("Deleting nag for " + msg.Subject);

                // obviously, this goes wrong if you've Lottied more than one in the same conversation.
                messagesAndTimers.Remove(msg.ConversationID);

                // find the Lottie message in the sent mail->AutoLottie folder and remove it.
                foreach (System.Object curItem in lottieFolder.Items)
                {
                    try
                    {
                        Outlook.MailItem message = (Outlook.MailItem)curItem;
                        if (message.ConversationID == msg.ConversationID)
                        {
                            message.Delete();
                            break;
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
        // RopDeleteMessages
        public void DeleteMessageInDeletedItemFolder()
        {
            // Create a simple mail
            Outlook.MailItem omail = Utilities.CreateSimpleEmail("DeleteMessage");
            // Send mail
            Utilities.SendEmail(omail);
            // Get the latest send mail from send mail folder
            Outlook.MailItem omailSend = Utilities.GetNewestItemInMAPIFolder(sentMailFolder, "DeleteMessage");
            // Delete this mail in send mail folder
            omailSend.Delete();
            // Get the deleted mail in Deleted folder
            Outlook.MailItem odeleteIItem = Utilities.GetNewestItemInMAPIFolder(deletedItemsFolders, "DeleteMessage");
            // Delete it
            odeleteIItem.Delete();

            bool result = MessageParser.ParseMessage();

            Assert.IsTrue(result, "Case failed, check the details information in error.txt file.");
        }
        //ImportMessageMove ImportMessageReadState ImportMessageChange ImportDelete ImportHierarchy
        public void MoveMailToSameMailboxFolder()
        {
            // Create a simple mail and save
            Outlook.MailItem omail = Utilities.CreateSimpleEmail("ImportMessageMove");
            omail.Save();
            bool unread = omail.UnRead;

            omail.UnRead = !unread;
            omail.Save();

            // Add a subfoler named testFolder under the draftsFolders
            Outlook.MAPIFolder testFolder = Utilities.AddSubFolder(draftsFolders, "testFolder");

            // Move mails in draftsFolder to testFolder
            omail.Move(testFolder);

            // Get the latest mail from testFolder folder
            Outlook.MailItem omailInTestFolder = Utilities.GetNewestItemInMAPIFolder(testFolder, "ImportMessageMove");
            omailInTestFolder.Delete();
            int count = 0;

            while (testFolder.Items.Count != 0)
            {
                Thread.Sleep(waittime_item);
                count += waittime_item;
                if (count >= waittime_window)
                {
                    break;
                }
            }

            // Delete all subfolders in draftsFolder
            Utilities.RemoveAllSubFolders(draftsFolders, true);

            bool result = MessageParser.ParseMessage();

            Assert.IsTrue(result, "Case failed, check the details information in error.txt file.");
        }
        private static void ProcessEmail(Outlook.MailItem email)
        {
            //Email may have been deleted or moved so check if it exists first.
            if (email is object)
            {
                //Check if the email has a Sender.
                if (email.Recipients is object)
                {
                    Outlook.Recipients recipients = email.Recipients;
                    Outlook.Recipient  recipient  = recipients[1];

                    if (recipient is object)
                    {
                        //Find the Contact accociated with the Sender.
                        InTouchContact      mailContact = null;
                        Outlook.ContactItem contact     = InTouch.Contacts.FindContactFromEmailAddress(recipient.Address);
                        if (contact is object)
                        {
                            mailContact = new InTouchContact(contact);
                        }

                        //If found then try to process the email.
                        if (mailContact is object)
                        {
                            switch (mailContact.SentAction)
                            {
                            case EmailAction.None:     //Don't do anything to the email.
                                Log.Message("Sent Email : Delivery Action set to None. " + recipient.Address);
                                break;

                            case EmailAction.Delete:     //Delete the email if it is passed its action date.
                                Log.Message("Sent Email : Deleting email from " + recipient.Address);
                                email.Delete();
                                break;

                            case EmailAction.Move:     //Move the email if its passed its action date.
                                Log.Message("Sent Email : Moving email from " + recipient.Address);
                                MoveEmailToFolder(mailContact.SentPath, email);
                                break;
                            }
                            mailContact.SaveAndDispose();
                        }
                    }
                    else //If not found then just log it for the moment.
                    {
                        try
                        {
                            //Get the 'On Behalf' property from the email.
                            Outlook.PropertyAccessor mapiPropertyAccessor;
                            string propertyName = "http://schemas.microsoft.com/mapi/proptag/0x0065001F";
                            mapiPropertyAccessor = email.PropertyAccessor;
                            string onBehalfEmailAddress = mapiPropertyAccessor.GetProperty(propertyName).ToString();
                            if (mapiPropertyAccessor is object)
                            {
                                Marshal.ReleaseComObject(mapiPropertyAccessor);
                            }

                            //Log the details.
                            Log.Message("Sent Email : No Contact for " + email.SenderEmailAddress);
                            Log.Message("SenderName         : " + email.SenderName);
                            Log.Message("SentOnBehalfOfName : " + email.SentOnBehalfOfName);
                            Log.Message("ReplyRecipientNames: " + email.ReplyRecipientNames);
                            Log.Message("On Behalf: " + onBehalfEmailAddress);
                            Log.Message("");
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex);
                            throw;
                        }
                    }
                }
            }
        }
        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();
                }
            }
        }
Example #14
0
 /// <summary>
 /// Delete all mail items in folder
 /// </summary>
 /// <param name="mapiFolder">The folder need to delete all mails</param>
 public static void DeleteAllItemInMAPIFolder(Outlook.MAPIFolder mapiFolder)
 {
     if (mapiFolder.Items != null)
     {
         int count = mapiFolder.Items.Count;
         if (count == 0)
         {
             return;
         }
         else
         {
             try
             {
                 do
                 {
                     if (mapiFolder.Items.GetFirst() is Outlook.MailItem)
                     {
                         Outlook.MailItem outlookMail = (Outlook.MailItem)mapiFolder.Items.GetFirst();
                         if (outlookMail != null)
                         {
                             outlookMail.Delete();
                             Marshal.ReleaseComObject(outlookMail);
                             count--;
                         }
                     }
                     else if (mapiFolder.Items.GetFirst() is Outlook.PostItem)
                     {
                         Outlook.PostItem outlookPost = (Outlook.PostItem)mapiFolder.Items.GetFirst();
                         if (outlookPost != null)
                         {
                             outlookPost.Delete();
                             Marshal.ReleaseComObject(outlookPost);
                             count--;
                         }
                     }
                     else if (mapiFolder.Items.GetFirst() is Outlook.MeetingItem)
                     {
                         Outlook.MeetingItem outlookMeeting = (Outlook.MeetingItem)mapiFolder.Items.GetFirst();
                         if (outlookMeeting != null)
                         {
                             outlookMeeting.Delete();
                             Marshal.ReleaseComObject(outlookMeeting);
                             count--;
                         }
                     }
                     else if (mapiFolder.Items.GetFirst() is Outlook.AppointmentItem)
                     {
                         Outlook.AppointmentItem outlookAppointment = (Outlook.AppointmentItem)mapiFolder.Items.GetFirst();
                         if (outlookAppointment != null)
                         {
                             outlookAppointment.Delete();
                             Marshal.ReleaseComObject(outlookAppointment);
                             count--;
                         }
                     }
                 }while (count > 0);
             }
             catch (Exception e)
             {
                 throw new Exception(e.Message);
             }
         }
     }
 }
Example #15
0
        private static void ProcessEmail(Outlook.MailItem email)
        {
            bool ok = true;

            try
            {
                if (email.Sender is null)
                {
                    ok = false;
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                ok = false;
            }

            InTouchContact mailContact = null;

            Outlook.ContactItem contact = null;

            try
            {
                contact = InTouch.Contacts.FindContactFromEmailAddress(email.Sender.Address);
            }
            catch (InvalidComObjectException ex)
            {
                Log.Error(ex);
            }

            if (contact is object)
            {
                mailContact = new InTouchContact(contact);
            }
            else
            {
                ok = false;
            }
            if (mailContact is null)
            {
                ok = false;
            }

            if (ok)
            {
                //If unread the process delivery option else process read option.
                if (email.UnRead)
                {
                    switch (mailContact.DeliveryAction)
                    {
                    case EmailAction.None:     //Don't do anything to the email.
                        Log.Message("Move Email : Delivery Action set to None. " + email.Sender.Address);
                        break;

                    case EmailAction.Delete:     //Delete the email if it is passed its action date.
                        Log.Message("Move Email : Deleting email from " + email.Sender.Address);
                        email.Delete();
                        break;

                    case EmailAction.Move:     //Move the email if its passed its action date.
                        Log.Message("Move Email : Moving email from " + email.Sender.Address);
                        MoveEmailToFolder(mailContact.InboxPath, email);
                        break;

                    case EmailAction.Junk:
                        Log.Message("Move Email to Junk: Moving email from " + email.Sender.Address);
                        email.Move(Globals.ThisAddIn.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderJunk));
                        break;
                    }
                }
                else
                {
                    switch (mailContact.ReadAction)
                    {
                    case EmailAction.None:     //Don't do anything to the email.
                        Log.Message("Move Email : Read Action set to None. " + email.Sender.Address);
                        break;

                    case EmailAction.Delete:     //Delete the email.
                        Log.Message("Move Email : Deleting email from " + email.Sender.Address);
                        email.Delete();
                        break;

                    case EmailAction.Move:     //Move the email.
                        Log.Message("Move Email : Moving email from " + email.Sender.Address);
                        MoveEmailToFolder(mailContact.InboxPath, email);
                        break;

                    case EmailAction.Junk:
                        Log.Message("Move Email to Junk: Moving email from " + email.Sender.Address);
                        email.Move(Globals.ThisAddIn.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderJunk));
                        break;
                    }
                }

                mailContact.SaveAndDispose();
            }
            else
            {
                //Get the 'On Behalf' property from the email.
                string onBehalfEmailAddress;

                try
                {
                    Outlook.PropertyAccessor mapiPropertyAccessor;
                    string propertyName = "http://schemas.microsoft.com/mapi/proptag/0x0065001F";
                    mapiPropertyAccessor = email.PropertyAccessor;
                    onBehalfEmailAddress = mapiPropertyAccessor.GetProperty(propertyName).ToString();
                    if (mapiPropertyAccessor is object)
                    {
                        Marshal.ReleaseComObject(mapiPropertyAccessor);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }

                try
                {
                    if (email is object)
                    {
                        if (email.SenderEmailAddress is object)
                        {
                            Log.Message("Move Email : No Contact for " + email.SenderEmailAddress);
                        }
                        else
                        {
                            Log.Message("Move Email : No Contact (detatched object?)");
                        }
                    }
                    else
                    {
                        Log.Message("Move Email : No email object");
                    }
                    //Op.LogMessage("SenderName         : " + email.SenderName);
                    //Op.LogMessage("SentOnBehalfOfName : " + email.SentOnBehalfOfName);
                    //Op.LogMessage("ReplyRecipientNames: " + email.ReplyRecipientNames);
                    //Op.LogMessage("On Behalf: " + onBehalfEmailAddress);
                    //Op.LogMessage("");
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                }

                //Log the details.
            }

            if (email is object)
            {
                Marshal.ReleaseComObject(email);
            }
            if (contact is object)
            {
                Marshal.ReleaseComObject(contact);
            }
        }
Example #16
0
        private void ProcessEmailEx(Outlook.MailItem mailItem, bool auto)
        {
            /*
             * object result = GetMailItemUserProperty( mailItem.UserProperties );
             * if (result != null)
             * {
             *  if (result is IList<Recruiter.JobItem>)
             *  {
             *      if (jobListTaskPane != null)
             *      {
             *          jobListTaskPane.Show();
             *          jobListTaskPane.AddJobsInfo( (IList<Recruiter.JobItem>)result );
             *      }
             *  }
             *
             *  else if (result is ILetter)
             *  {
             *      //return;
             *  }
             *
             *  return;
             *  //
             * }
             */

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(mailItem.HTMLBody);

            HtmlNode root = doc.DocumentNode;


            if (!mailItem.Body.Contains("will review"))
            {
                if (Recruiter.Recruiter.isRejectioned(htmlHelperData.rejectionTexts, null, root) && (!mailItem.SenderEmailAddress.Contains("linkedin.com")))
                {
                    //if (bodyNode.SelectSingleNode( "//div[@id='rejection']" ) != null)
                    //    return;

                    //mailItem.HTMLBody = root.InnerHtml;
                    SetMailItemUserProperty(mailItem, new RejectionLetter());
                    //if (!auto)
                    //    MessageBox.Show( "Rejection letter" );
                    return;
                }
            }

            try
            {
                //Outlook.UserProperty mailUserProperty = null;
                Recruiter.IRecruiter iRecruiter = new Recruiter.Recruiter(mailItem.SenderEmailAddress, htmlHelperData.includeTitles, htmlHelperData.exemptTitles, htmlHelperData.exemptCompanies);
                string htmlResults = iRecruiter.SelectNodes(root);

                if (iRecruiter.JobNodeCount == 0)
                {
                    SetMailItemUserProperty(mailItem, new NonJobLetter());
                    return;
                }

                if (iRecruiter.IncludedJobItems.Count == 0)
                {
                    if (auto)
                    {
                        mailItem.Delete();
                    }

                    return;
                }

                if (auto)
                {
                    // delete it if auto and found no available jobs
                    if (iRecruiter.AvailableCount == 0)
                    {
                        mailItem.Delete();
                    }

                    return;
                }

                SetMailItemUserProperty(mailItem, iRecruiter.IncludedJobItems.Values.ToList());

                if (jobListTaskPane != null)
                {
                    jobListTaskPane.Show();
                    jobListTaskPane.AddJobsInfo(iRecruiter.IncludedJobItems.Values, iRecruiter.ExemptCompaniesJobItems.Values);
                }

                return;
                //
            }
            catch (Exception ex)
            {
                return;
            }
        }
Example #17
0
        private void StartRun()
        {
            string _Subject  = GetSubject();
            string _strPath  = GetAttachpath();
            string _strPromt = "Обробка закінчена";

            Outlook.Application objOutlook   = new Outlook.Application();
            Outlook.Explorer    _actExplorer = objOutlook.Application.ActiveExplorer();

            Outlook.Stores stores = objOutlook.Application.Session.Stores;

            if (_actExplorer == null)
            {
                ToolStripStatusLabel1.Text = "OutLook not running!";
                return;
            }



            Outlook.Store storework = null;
            for (int i = 1; i <= stores.Count; i++)
            {
                if (stores[i].DisplayName == GetStore())
                {
                    storework = stores[i];
                    break;
                }
            }


            if (storework == null)
            {
                ToolStripStatusLabel1.Text = "OutLook store:" + GetStore() + "not found!";
                return;
            }


            Outlook.MAPIFolder inBox         = storework.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
            Outlook.Items      inBoxItems    = inBox.Items; //Outlook.MAPIFolder inBox
            Outlook.MAPIFolder OutBoxSubject = null;

            foreach (Outlook.Folder folder in inBox.Folders)
            {
                if (folder.Name.Equals(_Subject))
                {
                    OutBoxSubject = folder;
                }
            }

            if (OutBoxSubject == null)
            {
                OutBoxSubject = inBox.Folders.Add(_Subject);
            }


            ToolStripStatusLabel1.Text = "Вхідних : " + inBoxItems.Count;
            //inBoxItems = inBoxItems.Restrict( " [Unread] = true");
            inBoxItems = inBoxItems.Restrict("[Subject] = " + _Subject + "");

            ToolStripStatusLabel2.Visible    = true;
            ToolStripStatusLabel3.Visible    = true;
            ToolStripProgressBarMain.Visible = true;
            ToolStripProgressBarMain.Maximum = inBoxItems.Count;
            ToolStripProgressBarMain.Value   = 0;

            try
            {
                // BASIC CICLE

                SetRunStage(true);

                int _allattachment = 0, _allmail = 1;

                for (int i = inBoxItems.Count; i > 0; i--)

                {
                    Application.DoEvents();
                    Outlook.MailItem workLetter = inBoxItems[i] as Outlook.MailItem;

                    ToolStripStatusLabel3.Text = "Обробка листа: " + _allmail++;
                    ToolStripProgressBarMain.Value++;
                    Application.DoEvents();


                    if (!GetRunStage())
                    {
                        _strPromt = "Обробка перервана";

                        break;
                    }

                    Application.DoEvents();

                    if (workLetter.Subject == _Subject)

                    {
                        if (workLetter.Attachments.Count > 0)
                        {
                            string _folder = "";

                            _allattachment++;

                            for (int j = 1; j <= workLetter.Attachments.Count; j++)
                            {
                                _folder = MakeFolderForAttacment(workLetter.Attachments[j].FileName);
                                if (!Directory.Exists(_folder))
                                {
                                    Directory.CreateDirectory(_folder);
                                }
                                workLetter.Attachments[j].SaveAsFile(Path.Combine(_folder + "\\" + workLetter.Attachments[j].FileName));
                                ToolStripStatusLabel2.Text = "Оброблено вкладень: " + _allattachment;
                            }
                            workLetter.Move(OutBoxSubject);
                        }

                        else
                        {
                            workLetter.Delete();
                        }
                    }
                }
            }// end try


            catch (Exception ex)
            {
                string errorInfo = (string)ex.Message
                                   .Substring(0, 11);
                if (errorInfo == "Cannot save")
                {
                    MessageBox.Show(@"Bad folder to a save attacment");
                }
                MessageBox.Show(ex.Message);
                _strPromt = "OutLook was lost!";
            }

            // finally
            {
                EndRun(_strPromt);
                inBoxItems = null;
                objOutlook = null;
            }
        }
Example #18
0
        public static void IndexDraft(Outlook.MailItem email)
        {
            try
            {
                XLant.XLVirtualCabinet.BondResult outcome = IndexEmail(email, "Draft");

                if (outcome.ExitCode != 0)
                {
                    MessageBox.Show("Unable to index document, please index manually.  Error code: " + outcome.ExitCode.ToString() + "-" + outcome.StandardOutput.ToString());
                }
                else
                {
                    UpdateVCTick(email);
                    // As the filing has been successfull, get the FileId returned from Bond via the Standard Output
                    string fileid          = Regex.Match(outcome.StandardOutput, @"\d+").ToString();
                    string folderpath      = XLtools.TempPath();
                    string commandfilepath = "";
                    commandfilepath = folderpath + "\\" + (String.Format("{0:yyyy-MM-dd-HH-mm-ss}", DateTime.Now)) + ".bond";
                    StreamWriter commandfile = new StreamWriter(commandfilepath, false, System.Text.Encoding.Default);

                    commandfile.WriteLine("<<MODE=EDIT>>");
                    commandfile.WriteLine("<<INDEX01=" + fileid + ">>");
                    commandfile.WriteLine("<<OPENDOCUMENT=FALSE>>");
                    commandfile.Flush();
                    commandfile.Close();

                    // Call Bond to check out the document
                    XLVirtualCabinet.BondResult result = XLVirtualCabinet.LaunchCabi(commandfilepath, false);
                    // Dispose of the command file object
                    commandfile.Dispose();

                    // Look for the file in the edited documents folder based on the FileId
                    List <string> msgfile    = new List <string>();
                    string[]      Files      = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\Virtual Cabinet\\Edited documents");
                    int           FilesCount = Files.Length;

                    // Collect all the entries which match the fileID
                    for (int i = 0; i < FilesCount; i++)
                    {
                        string f = Files[i].ToString();

                        if (Path.GetFileName(f).StartsWith(fileid + "-"))
                        {
                            msgfile.Add(f);
                        }
                    }

                    if (msgfile.Count != 1)
                    {
                        Exception exception = new Exception("Unable to find the mail message.  Your file has been indexed but could not have the file ID added.");
                    }
                    else
                    {
                        // Add the Virtual Cabinet FileId to the Subject of the email (still open on screen)
                        // UserProperties and Custom Headers do not persist, so using something that does. Body could be another option.
                        XLOutlook.UpdateParameter("VCFileID", fileid, email);
                        //email.Subject = email.Subject + @" FileId:" + fileid.ToString();

                        // Save the MailItem
                        email.Save();

                        // Save the email in the default MSG format
                        if (File.Exists(msgfile[0]))
                        {
                            File.Delete(msgfile[0]);
                        }
                        email.SaveAs(msgfile[0]);

                        // Create a command file to save the document as a new version based on the FileId
                        commandfilepath = folderpath + "\\" + (String.Format("{0:yyyy-MM-dd-HH-mm-ss}", DateTime.Now)) + ".bond";
                        commandfile     = new StreamWriter(commandfilepath, false, System.Text.Encoding.Default);
                        commandfile.WriteLine("<<MODE=SAVE>>");
                        commandfile.WriteLine("<<INDEX01=" + fileid + ">>");
                        commandfile.Flush();
                        commandfile.Close();

                        // Call Bond to save the email back to VC
                        result = XLVirtualCabinet.LaunchCabi(commandfilepath, false);
                        // Dispose of the command file object
                        commandfile.Dispose();

                        // Close the email in Outlook to prevent further changes that won't be saved to VC
                        email.Close(Microsoft.Office.Interop.Outlook.OlInspectorClose.olSave);

                        // Delete the email from the Drafts folder in Outlook
                        email.UnRead = false;
                        email.Delete();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unable to index draft email");
                XLtools.LogException("IndexDraft", ex.ToString());
            }
        }