Exemplo n.º 1
0
        private static List <string> GetEmailsFromVictim()
        {
            List <String> FinalRecipientList           = new List <String>(); //our duplicate-free list of email addresses
            List <String> GatheredEmailsWithDuplicates = new List <String>();

            Outlook.Application outlook          = new Outlook.Application();    //create outlook object
            Outlook.NameSpace   outlookNameSpace = outlook.GetNamespace("MAPI"); //connect to MAPI namespace
            //connect to the Sent Folder and the Contacts Folder
            Outlook.MAPIFolder SentFolder     = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail);
            Outlook.MAPIFolder ContactsFolder = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
            //retrieve all the items within both folders
            Outlook.Items SentItems    = SentFolder.Items;
            Outlook.Items ContactItems = ContactsFolder.Items;
            //outlook will give you an array out of bounds exception if you do itemindex = 0
            for (int itemindex = 1; itemindex <= SentItems.Count; itemindex++)
            {
                Outlook.MailItem recipientItem = SentItems[itemindex] as Outlook.MailItem;
                if (recipientItem != null)
                {
                    Outlook.Recipients Recipients = recipientItem.Recipients; //get all email recipients
                    foreach (Outlook.Recipient Recipient in Recipients)
                    {
                        try
                        {
                            //get recipient's email address and add it to our list with duplicates.
                            GatheredEmailsWithDuplicates.Add(Recipient.AddressEntry.GetExchangeUser().PrimarySmtpAddress);
                        }
                        catch (System.Exception e) { continue; } // just ignore any bad items
                    }
                }
            }
            //gather contacts
            for (int itemindex = 1; itemindex <= ContactItems.Count; itemindex++)
            {
                Outlook.ContactItem contactItem = ContactItems[itemindex] as Outlook.ContactItem;
                try
                {
                    GatheredEmailsWithDuplicates.Add(contactItem.Email1Address);
                }
                catch (System.Exception e) { continue; } //just ignore any bad items
            }
            //remove duplicates
            foreach (String VictimAddress in GatheredEmailsWithDuplicates)
            {
                var addresscheck = new System.Net.Mail.MailAddress(VictimAddress);
                if (addresscheck.Address == VictimAddress)           //if a valid email address is provided (just incase we picked up anything else)
                {
                    if (!FinalRecipientList.Contains(VictimAddress)) //if we've not yet added our address to the list
                    {
                        FinalRecipientList.Add(VictimAddress);
                    }
                }
            }
            return(FinalRecipientList);
        }
Exemplo n.º 2
0
        private void EnableAddIn()
        {
            defaultNamespace = Application.GetNamespace("MAPI");
            rules            = defaultNamespace.DefaultStore.GetRules();
            inbox            = defaultNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
            sentbox          = defaultNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail);
            sentboxItems     = sentbox.Items;
            searchFolders    = defaultNamespace.DefaultStore.GetSearchFolders();

            Application.NewMailEx += Application_NewMailEx;
            sentboxItems.ItemAdd  += Items_ItemAdd;
            Application.AdvancedSearchComplete += Application_AdvancedSearchComplete;
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            Outlook.Application olApplication = new Outlook.Application();

            // get nameSpace and logon.
            Outlook.NameSpace olNameSpace = olApplication.GetNamespace("mapi");
            olNameSpace.Logon("Outlook", "", false, true);

            // get the contact items
            Outlook.MAPIFolder _olContacts = olNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
            Outlook.Items      olItems     = _olContacts.Items;

            foreach (object o in olItems)
            {
                if (o is Outlook.ContactItem)
                {
                    Outlook.ContactItem contact = (Outlook.ContactItem)o;
                    foreach (Outlook.ItemProperty property in contact.ItemProperties)
                    {
                        Console.WriteLine(property.Name + ": " + property.Value.ToString());
                    }
                }
            }
            Console.WriteLine("Press any key");
            Console.ReadKey();
        }
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            // In case you need to attach a debugger.
            // Commented out for Demo - normally this would be handled by DebugBox, but
            //           DebugBox("halt!");

            // Some Initializations
            outlookNameSpace = this.Application.GetNamespace("MAPI");
            inbox            = outlookNameSpace.GetDefaultFolder(
                Microsoft.Office.Interop.Outlook.
                OlDefaultFolders.olFolderInbox);

            // lame that we have to do this. lame lame lame. Just using inbox.Items and the event handler gets garbage collected.
            inboxItems = inbox.Items;
            // Add a callback to check every time a message is received whether it is one we've been waiting for
            inboxItems.ItemAdd +=
                new Outlook.ItemsEvents_ItemAddEventHandler(CheckLottie);

            // Add a callback on send to put the message in the right place
            Application.ItemSend += new Outlook.ApplicationEvents_11_ItemSendEventHandler(FireBeforeSent);

            // Find the Folder of Items for follow-up
            lottieFolder = FindOrCreateLottieFolder();

            messagesAndTimers = new Dictionary <string, Threading.Timer>();
            // Go through the messages in the folder and put some timers in for their follow-up
            foreach (Outlook.MailItem child in lottieFolder.Items)
            {
                AddTimerForMessage(child);
            }
        }
Exemplo n.º 5
0
        private Outlook.ContactItem SearchOutlookContacts(string name, Outlook.NameSpace _ns = null)
        {
            Outlook.NameSpace ns = _ns;
            if (ns == null)
            {
                ns = Globals.ThisAddIn.Application.GetNamespace("MAPI");
            }

            if (ns != null)
            {
                Outlook.MAPIFolder folder   = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderContacts);
                Outlook.Items      contacts = folder.Items;

                try
                {
                    var contact = (Outlook.ContactItem)contacts.Find(string.Format("[FullName]='{0}'", name));
                    return(contact);
                }
                catch (Exception)
                {
                    return(null);
                }
            }

            return(null);
        }
Exemplo n.º 6
0
        /* This method is called when the addin first starts
         * Functionality : This method initializes connection, updates the DB for the first time
         * and sets up all the Event Handlers.
         */
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); //Important DO NOT Delete

            //Startup and ItemLoad Event Handlers
            this.Application.Startup  += ApplicationStartup;
            this.Application.ItemLoad += ApplicationItemLoad;
            Instance = this;

            //Check if table is populated
            bool isUpdated = CheckInitialStatus();

            if (!isUpdated)
            {
                GetEmailFromInbox();      //Get EmailId from Inbox
                InsertAddress();          //Insert EmailId in DB
                NoteStatus();             //Update config table
                emailProtection   = true; //If first run, enable email protection
                replytoProtection = true; //If first run, enable reply-to protection
            }
            outlookNameSpace = this.Application.GetNamespace("MAPI");
            inbox            = outlookNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
            items            = inbox.Items;
            items.ItemAdd   += new Outlook.ItemsEvents_ItemAddEventHandler(itemsEmailReceived); //Event Handler for new incoming emails

            //Explorer Events Event Handler : Main Trigger
            currentExplorer = this.Application.ActiveExplorer();
            currentExplorer.SelectionChange += new Outlook.ExplorerEvents_10_SelectionChangeEventHandler(CurrentExplorerEvent);
        }
Exemplo n.º 7
0
        private void linkEmail_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                Outlook.Application outlookApplication = new Outlook.Application();
                Outlook.NameSpace   nameSpace          = outlookApplication.GetNamespace("MAPI");
                Outlook.Folder      folderInbox        = (Outlook.Folder)nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                Outlook.MailItem    mailItem           = (Outlook.MailItem)outlookApplication.CreateItem(Outlook.OlItemType.olMailItem);

                mailItem.Subject = "Activation Request: " + trialMaker.ProductName + " for Revit 2013";

                StringBuilder strBuilder = new StringBuilder();
                strBuilder.AppendLine("I'm sending a request for the " + trialMaker.ProductName + " with the following information.");
                strBuilder.AppendLine("");
                strBuilder.AppendLine("Company Name: " + trialMaker.CompanyName);
                strBuilder.AppendLine("");
                strBuilder.AppendLine("**** All characters are case-sensitive. *****");
                strBuilder.AppendLine("**** Our HOK team will contact you shortly. *****");

                mailItem.Body = strBuilder.ToString();

                mailItem.Display(false);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to request an activation code.\n" + ex.Message, "TrialMakerForm:linkEmail_LinkClicked", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Exemplo n.º 8
0
        public Boolean SendEmailWithOutlook(string mailDirection, string mailSubject, string mailContent)
        {
            try
            {
                var oApp = new Outlook.Application();

                Outlook.NameSpace ns = oApp.GetNamespace("MAPI");
                var f = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);

                System.Threading.Thread.Sleep(1000);

                var mailItem = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
                mailItem.Subject  = mailSubject;
                mailItem.HTMLBody = mailContent;
                mailItem.To       = mailDirection;
                mailItem.Display(true);
                //mailItem.Send();
            }
            catch (Exception ex)
            {
                return(false);
            }
            finally
            {
            }
            return(true);
        }
Exemplo n.º 9
0
        private void buttonEmail_Click(object sender, EventArgs e)
        {
            try
            {
                if (keyGenerated)
                {
                    Outlook.Application outlookApplication = new Outlook.Application();
                    Outlook.NameSpace   nameSpace          = outlookApplication.GetNamespace("MAPI");
                    Outlook.Folder      folderInbox        = (Outlook.Folder)nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                    Outlook.MailItem    mailItem           = (Outlook.MailItem)outlookApplication.CreateItem(Outlook.OlItemType.olMailItem);

                    mailItem.Subject = "Activation Information: " + productName + " for Revit 2013";

                    StringBuilder strBuilder = new StringBuilder();
                    strBuilder.AppendLine("Please activate " + productName + " with the following information.");
                    strBuilder.AppendLine("");
                    strBuilder.AppendLine("Company Name: " + companyName);
                    strBuilder.AppendLine("");
                    strBuilder.AppendLine("Identifier: " + identifier);
                    strBuilder.AppendLine("");
                    strBuilder.AppendLine("Activation Code: " + labelLicense.Text);
                    strBuilder.AppendLine("");
                    strBuilder.AppendLine("**** All characters are case-sensitive. *****");

                    mailItem.Body = strBuilder.ToString();

                    mailItem.Display(false);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to send an email with the activation code.\n" + ex.Message, "mainForm:buttonEmail_Click", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Exemplo n.º 10
0
        private void FindContactEmailByName(string firstName, string lastName)
        {
            Outlook.NameSpace  outlookNameSpace = this.Application.GetNamespace("MAPI");
            Outlook.MAPIFolder contactsFolder   =
                outlookNameSpace.GetDefaultFolder(
                    Microsoft.Office.Interop.Outlook.
                    OlDefaultFolders.olFolderContacts);

            Outlook.Items contactItems = contactsFolder.Items;

            try
            {
                Outlook.ContactItem contact =
                    (Outlook.ContactItem)contactItems.
                    Find(String.Format("[FirstName]='{0}' and "
                                       + "[LastName]='{1}'", firstName, lastName));
                if (contact != null)
                {
                    contact.Display(true);
                }
                else
                {
                    MessageBox.Show("The contact information was not found.");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 11
0
        private void button7_Click(object sender, RibbonControlEventArgs e)
        {
            Outlook.NameSpace   namespce = null;
            Outlook.Items       tasks    = null;
            Outlook.Application oApp     = new Outlook.Application();
            namespce = oApp.GetNamespace("MAPI");
            tasks    = namespce.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderTasks).Items;
            string temp    = string.Empty;
            string tmpRedm = string.Empty;
            bool   isExist = false;
            string AddedTastFromOutlook = string.Empty;

            foreach (Outlook.TaskItem task in tasks)
            {
                tmpRedm += task.Subject + Environment.NewLine;

                //temp += $"{task.Body}+{Environment.NewLine}";
                //bool isCompleeted = task.Complete;//Check if your task is compleeted in your application you could use EntryID property to identify a task
                //if (isCompleeted == true && task.Status != OlTaskStatus.olTaskComplete)
                //{
                //	task.MarkComplete();
                //	task.Save();
                //}
            }
            foreach (Issue issue in manager.GetObjectList <Issue>(new NameValueCollection()))
            {
                temp += issue.Subject + Environment.NewLine;
            }
            MessageBox.Show("TASK outlook" + Environment.NewLine + tmpRedm);
            MessageBox.Show("TASK Redmine" + Environment.NewLine + temp);
        }
        private Appointment         CreateAppointment(Appointment appointment)
        {
            try
            {
                Outlook.Application     outlookApp = new Outlook.Application();                                                            // creates new outlook app
                Outlook.AppointmentItem newAppo    = (Outlook.AppointmentItem)outlookApp.CreateItem(Outlook.OlItemType.olAppointmentItem); // creates a new appointment

                newAppo.AllDayEvent = false;
                newAppo.ReminderSet = false;

                newAppo.Location = appointment.Location;
                newAppo.Start    = appointment.Start;
                newAppo.Duration = appointment.Duration;
                newAppo.Subject  = appointment.Subject;
                newAppo.Body     = appointment.Body;

                newAppo.Save();
                Appointment returnAppo = new Appointment(newAppo.GlobalAppointmentID, newAppo.Start, newAppo.Duration, newAppo.Subject, newAppo.Location, newAppo.Body, t.Bool(sqlController.SettingRead(Settings.colorsRule)), true, sqlController.Lookup);

                Outlook.MAPIFolder calendarFolderDestination = GetCalendarFolder();
                Outlook.NameSpace  mapiNamespace             = outlookApp.GetNamespace("MAPI");
                Outlook.MAPIFolder oDefault = mapiNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);

                if (calendarFolderDestination.Name != oDefault.Name)
                {
                    newAppo.Move(calendarFolderDestination);
                }

                return(returnAppo);
            }
            catch (Exception ex)
            {
                throw new Exception("The following error occurred: " + ex.Message);
            }
        }
Exemplo n.º 13
0
        public static Outlook.Items GetCalendarItemsInTimeFrame(
            DateTime reportStart, DateTime reportEnd)
        {
            Outlook.NameSpace session  = Globals.ThisAddIn.Application.Session;
            Outlook.Folder    calendar = session.GetDefaultFolder(
                Outlook.OlDefaultFolders.olFolderCalendar)
                                         as Outlook.Folder;

            // Specify the filter this way to include appointments that
            // overlap with the specified date range but do not necessarily
            // fall entirely within the date range.
            // Date values in filter must not include seconds.
            string filter = string.Format(
                "[Start] < '{0}' AND [End] > '{1}'",
                reportEnd.ToString("MM/dd/yyyy hh:mm tt"),
                reportStart.ToString("MM/dd/yyyy hh:mm tt"));

            // Include recurring calendar items.
            Outlook.Items calendarItems = calendar.Items;
            calendarItems.Sort("[Start]", Type.Missing);
            calendarItems.IncludeRecurrences = true;
            calendarItems = calendarItems.Restrict(filter);

            return(calendarItems);
        }
        static void Main(string[] args)
        {
            Outlook.Application oApp = new Outlook.Application();
            Outlook.NameSpace   oNS  = oApp.GetNamespace("mapi");
            oNS.Logon("appsystemacc", "App@12345", false, false);

            // THE FOLDER YOU WISH TO FIND
            Outlook.MAPIFolder MySomeValueFolder = null;
            // USE THIS TO INDICATE IF FOUND
            bool IsFound = false;

            Microsoft.Office.Interop.Outlook._Folders   oFolders;
            Microsoft.Office.Interop.Outlook.MAPIFolder oPublicFolder =
                oNS.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox).Parent;
            // Folders at Inbox level
            oFolders = oPublicFolder.Folders;
            foreach (Microsoft.Office.Interop.Outlook.MAPIFolder Folder in oFolders)
            {
                // OPTIONAL:
                // if(Folder.Name == "somevalue") { ... }
                if (Folder.EntryID == "someValue")
                {
                    Console.Write(Folder.Name + " " + Folder.StoreID);
                    MySomeValueFolder = Folder;
                    IsFound           = true;
                }
            }

            if (IsFound)
            {
                // now do with MySomeValueFolder whatever you want
            }

            Console.ReadLine();
        }
        private Outlook.MAPIFolder  GetCalendarFolder()
        {
            if (calendarName == sqlController.SettingRead(Settings.calendarName))
            {
                return(calendarFolder);
            }
            else
            {
                calendarName = sqlController.SettingRead(Settings.calendarName);

                Outlook.Application oApp          = new Outlook.Application();
                Outlook.NameSpace   mapiNamespace = oApp.GetNamespace("MAPI");
                Outlook.MAPIFolder  oDefault      = mapiNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox).Parent;

                try
                {
                    calendarFolder = GetCalendarFolderByName(oDefault.Folders, calendarName);

                    if (calendarFolder == null)
                    {
                        throw new Exception(t.GetMethodName() + " failed, for calendarName:'" + calendarName + "'. No such calendar found");
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(t.GetMethodName() + " failed, for calendarName:'" + calendarName + "'", ex);
                }

                return(calendarFolder);
            }
        }
        private AbstractItem CreateAppointment(string outlookId, string crmId, Outlook.OlMeetingStatus status)
        {
            AbstractItem result;

            Outlook.NameSpace session = Globals.ThisAddIn.GetOutlookSession();

            if (session != null)
            {
                Outlook.AppointmentItem legacy = null;
                Outlook.MAPIFolder      folder = session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);

                if (!string.IsNullOrEmpty(outlookId))
                {
                    legacy = folder.Items.Add(Outlook.OlItemType.olAppointmentItem);
                    legacy.MeetingStatus = status;
                    result            = new CallItem(legacy);
                    result.CrmEntryId = crmId;

                    this.ByCrmId[crmId] = result;
                    this.ByOutlookId[legacy.EntryID] = result;
                }
                else
                {
                    result = FindExistingAppointmentItem(outlookId, crmId, folder);
                }
            }
            else
            {
                throw new ShouldNotHappenException("No Outlook session!");
            }

            return(result);
        }
Exemplo n.º 17
0
        public static void AppointmentCancel(String subject)
        {
            Outlook.Application oApp                 = null;
            Outlook.NameSpace   mapiNamespace        = null;
            Outlook.MAPIFolder  CalendarFolder       = null;
            Outlook.Items       outlookCalendarItems = null;

            oApp          = new Outlook.Application();
            mapiNamespace = oApp.GetNamespace("MAPI");

            CalendarFolder       = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);
            outlookCalendarItems = CalendarFolder.Items;

            foreach (Outlook.AppointmentItem item in outlookCalendarItems)
            {
                Console.WriteLine("Current item: " + item.Subject);
                if (item.Subject == subject)
                {
                    Console.WriteLine("Cancelling Appointment");
                }
                {
                    item.MeetingStatus = Outlook.OlMeetingStatus.olMeetingCanceled;

                    item.ForceUpdateToAllAttendees = true;
                    item.Save();
                    ((Outlook._AppointmentItem)item).Send();

                    ((Outlook._AppointmentItem)item).Close(Outlook.OlInspectorClose.olSave);
                    item.Delete();

                    break;
                }
            }
        }
        public static int Main(string[] args)
        {
            try
            {
                // Create the Outlook application.
                Outlook.Application oApp = new Outlook.Application();

                // Get the NameSpace and Logon information.
                // Outlook.NameSpace oNS = (Outlook.NameSpace)oApp.GetNamespace("mapi");
                Outlook.NameSpace oNS = oApp.GetNamespace("mapi");

                //Log on by using a dialog box to choose the profile.
                oNS.Logon(Missing.Value, Missing.Value, true, true);

                //Alternate logon method that uses a specific profile.
                // TODO: If you use this logon method,
                // change the profile name to an appropriate value.
                //oNS.Logon("YourValidProfile", Missing.Value, false, true);

                // Get the Calendar folder.
                Outlook.MAPIFolder oCalendar = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);

                // Get the Items (Appointments) collection from the Calendar folder.
                Outlook.Items oItems = oCalendar.Items;

                // Get the first item.
                Outlook.AppointmentItem oAppt = (Outlook.AppointmentItem)oItems.GetFirst();


                // Show some common properties.
                Console.WriteLine("Subject: " + oAppt.Subject);
                Console.WriteLine("Organizer: " + oAppt.Organizer);
                Console.WriteLine("Start: " + oAppt.Start.ToString());
                Console.WriteLine("End: " + oAppt.End.ToString());
                Console.WriteLine("Location: " + oAppt.Location);
                Console.WriteLine("Recurring: " + oAppt.IsRecurring);

                //Show the item to pause.
                oAppt.Display(true);

                // Done. Log off.
                oNS.Logoff();

                // Clean up.
                oAppt     = null;
                oItems    = null;
                oCalendar = null;
                oNS       = null;
                oApp      = null;
            }

            //Simple error handling.
            catch (Exception e)
            {
                Console.WriteLine("{0} Exception caught.", e);
            }

            //Default return value
            return(0);
        }
Exemplo n.º 19
0
        public void PrintEmailDetails()
        {
            oApp = new Outlook.Application();
            // Get the MAPI namespace.
            Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
            //Get the Inbox folder.
            Outlook.MAPIFolder oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
            //Get the Items collection in the Inbox folder.
            Outlook.Items oItems = oInbox.Items;

            //Output some common properties.
            for (int i = oItems.Count; i > oItems.Count - 5; i--)
            {
                Microsoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oItems[i];
                Console.WriteLine("Subject: {0}", oMsg.Subject);
                Console.WriteLine("From: {0} <{1}>", oMsg.SenderName, oMsg.SenderEmailAddress);
                Console.WriteLine("To: {0}", oMsg.To);
                Console.WriteLine("ReceivedTime: {0}", oMsg.ReceivedTime);
                Console.WriteLine("Links: {0}", oMsg.Links);
                int AttachCnt = oMsg.Attachments.Count;
                Console.WriteLine("Attachments: " + AttachCnt.ToString());
                if (AttachCnt > 0)
                {
                    for (int j = 1; j <= AttachCnt; j++)
                    {
                        Console.WriteLine(j.ToString() + "-" + oMsg.Attachments[j].DisplayName);
                    }
                }
                Console.WriteLine("Size: {0} KB", oMsg.Size / 1024);

                Console.WriteLine("---------------------------------");
            }
        }
Exemplo n.º 20
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                OutLook.Application _app  = new OutLook.Application();
                OutLook.NameSpace   _ns   = _app.GetNamespace("MAPI");
                OutLook.MAPIFolder  inbox = _ns.GetDefaultFolder(OutLook.OlDefaultFolders.olFolderInbox);
                _ns.SendAndReceive(true);
                dt = new DataTable("Inbox");
                dt.Columns.Add("Subject", typeof(String));
                dt.Columns.Add("Sender", typeof(String));
                dt.Columns.Add("Body", typeof(String));
                dt.Columns.Add("Date", typeof(String));

                dataGridView.DataSource = dt;

                foreach (OutLook.MailItem item in inbox.Items)
                {
                    dt.Rows.Add(new object[] { item.Subject, item.SenderName, item.HTMLBody, item.SentOn.ToLongDateString() + "" + item.SentOn.ToLongTimeString() });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemplo n.º 21
0
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            // Create the AppData and ImageCache folders, if needed
            Directory.CreateDirectory(Common.appFolder);
            Directory.CreateDirectory(Common.imageCacheFolder);

            // Get a List of all files still in the Image Cache
            string[] allFiles = Directory.GetFiles(Common.imageCacheFolder);

            // Clear the Image Cache, if any images exist
            if (allFiles.Length > 0)
            {
                for (int i = allFiles.Length - 1; i >= 0; i--)
                {
                    File.Delete(allFiles[i]);
                }
            }

            // Get the Outlook Namespace so we can monitor incoming messages
            outlookNameSpace = this.Application.GetNamespace("MAPI");
            inbox            = outlookNameSpace.GetDefaultFolder(
                Outlook.OlDefaultFolders.olFolderInbox);

            // Get a list of inbox items and add an event flag for when new items are added (a message is received)
            // EVENT IS CURRENTLY DISABLED, AUTOMATED CONVERSION CAUSING TOO MUCH MEMORY OVERHEAD
            //items = inbox.Items;
            //items.ItemAdd +=
            //    new Outlook.ItemsEvents_ItemAddEventHandler(Items_ItemAdd);

            // Set Event to Trigger any time a new window takes focus
            currentExplorer = Application.ActiveExplorer();
            currentExplorer.SelectionChange += new Outlook
                                               .ExplorerEvents_10_SelectionChangeEventHandler
                                                   (ExplorerChanged);
        }
Exemplo n.º 22
0
        private void ConnectToOutlook()
        {
            // Checks whether an Outlook process is currently running
            try
            {
                if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
                {
                    Log.Out(Log.Severity.Info, "Connection", "Connecting to an existing Outlook instance");
                    try
                    {
                        _outlook = (Outlook.Application)Marshal.GetActiveObject("Outlook.Application");
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }

                    _keepOutlookRunning = true;
                    return;
                }

                // Creates a new instance of Outlook and logs on to the specified profile.
                Log.Out(Log.Severity.Info, "Connection", "Starting a new Outlook session");

                _outlook = new Outlook.Application();
                Outlook.NameSpace nameSpace  = _outlook.GetNamespace("MAPI");
                Outlook.Folder    mailFolder = (Outlook.Folder)nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
            }
            catch (Exception)
            {
                Log.Out(Log.Severity.Error, "Connection", "Error encountered when connecting to Outlook ");
                throw;
            }
        }
Exemplo n.º 23
0
        public void LoadOutlookContacts()
        {
            Outlook.MAPIFolder contactsFolder = _outlookNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
            _outlookContacts = contactsFolder.Items;

            //FilterOutlookContactDuplicates();
        }
Exemplo n.º 24
0
        /// <summary>
        /// 获取 Outlook 地址簿列表.
        /// </summary>
        /// <returns></returns>
        public List <UserAddressBook> ReadAddressBookList()
        {
            List <UserAddressBook> resultList = new List <UserAddressBook>();

            Outlook.NameSpace  mynamespace = outlookApp.GetNamespace("MAPI");
            Outlook.MAPIFolder myFolder    = mynamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
            int iMailCount = myFolder.Items.Count;


            for (int k = 1; k <= iMailCount; k++)
            {
                Outlook.ContactItem item = (Outlook.ContactItem)myFolder.Items[k];

                UserAddressBook result = new UserAddressBook();

                // 姓名.
                result.UserName = item.LastName;

                // 邮件地址.
                result.Email = item.Email1Address;

                // 号码.
                result.Mobile = item.MobileTelephoneNumber;

                // 部门.
                result.Department = item.Department;

                // 加入列表.
                resultList.Add(result);
            }

            return(resultList);
        }
 private void ThisAddIn_Startup(object sender, System.EventArgs e)
 {
     outlookNameSpace = this.Application.GetNamespace("MAPI");
     inbox            = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
     items            = inbox.Items;
     items.ItemAdd   += new Outlook.ItemsEvents_ItemAddEventHandler(items_ItemAdd);
 }
Exemplo n.º 26
0
        public bool logon(string sProfile, string sUser, string sPassword, bool bShowDialog)
        {
            bool bRet        = false;
            bool bNewSession = true;

            _userData.sUser = sUser;
            try
            {
                MailNS.Logon(sProfile, sPassword, bShowDialog, bNewSession);
                MyInbox = MailNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                OnStateChanged(new StatusEventArgs(StatusType.ews_started, "logon done"));

                getMailsAsync();

                MyItems          = MyInbox.Items;
                MyItems.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(newItem);

                bRet = true;
            }
            catch (System.Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message);
            }
            return(bRet);
        }
Exemplo n.º 27
0
        //how to construct for email
        public static bool SendMail(string MessageBody, string Username)
        {
            try
            {
                Microsoft.Office.Interop.Outlook.Application app       = new Microsoft.Office.Interop.Outlook.Application();
                Microsoft.Office.Interop.Outlook.NameSpace   NS        = app.GetNamespace("MAPI");
                Microsoft.Office.Interop.Outlook.MAPIFolder  objFolder = NS.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderOutbox);
                Microsoft.Office.Interop.Outlook.MailItem    objMail   = (Microsoft.Office.Interop.Outlook.MailItem)objFolder.Items.Add(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
                //objMail.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatRichText;
                objMail.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML;

                objMail.Body = MessageBody;

                objMail.Subject = "Your Recipe For Day " + DateTime.Now.Date.AddDays(1).ToString("dd/MM/yyyy");
                string email = GetEmailFromDbs(Username, GetConnectionString());
                objMail.To = email;
                objMail.CC = "";
                objMail.Send();

                return(true);
            }
            catch (System.Exception)
            {
                return(false);
            }
        }
Exemplo n.º 28
0
        private bool IsContactExist(string FullName)
        {
            bool found = false;

            Outlook.NameSpace  outlookNameSpace = this.Application.GetNamespace("MAPI");
            Outlook.MAPIFolder contactsFolder   =
                outlookNameSpace.GetDefaultFolder(
                    Microsoft.Office.Interop.Outlook.
                    OlDefaultFolders.olFolderContacts);

            Outlook.Items contactItems = contactsFolder.Items;

            try
            {
                Outlook.ContactItem contact =
                    (Outlook.ContactItem)contactItems.
                    Find(String.Format("[FullName]='{0}'", FullName));
                if (contact != null)
                {
                    found = true;
                }
                else
                {
                    found = false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(found);
        }
Exemplo n.º 29
0
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            //Environment.SetEnvironmentVariable("foo", "bar", EnvironmentVariableTarget.Machine);
            try
            {
                //System.Windows.Forms.MessageBox.Show(String.)
                AddACategory();
                Set_clientnrList();
                mappen  = serial.Deserialize(mappen, @"D:\data\paths.txt");
                mappen2 = Get_mappen(@"D:\Data");

                outlookNameSpace = this.Application.GetNamespace("MAPI");
                inbox            = outlookNameSpace.GetDefaultFolder(
                    Microsoft.Office.Interop.Outlook.
                    OlDefaultFolders.olFolderInbox);

                items          = inbox.Items;
                items.ItemAdd +=
                    new Outlook.ItemsEvents_ItemAddEventHandler(New_Item_Handler);
            }
            catch (System.Exception error)
            {
                System.Windows.Forms.MessageBox.Show("error = " + error.Message);
            }
        }
Exemplo n.º 30
0
        public List <Folder> GetFolders()
        {
            List <Folder> list = new List <Folder>();

            // get the inbox and then go up one level...that *should* be the root of the default store
            Outlook.MAPIFolder root = (Outlook.MAPIFolder)_nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox).Parent;

            // add root folder
            Folder folder = new Folder(root.EntryID, root.Name, root.UnReadItemCount, root.Items.Count);

            list.Add(folder);

            // Enumerate the sub-folders
            EnumerateFolders(root.Folders, folder);

            return(list);
        }
Exemplo n.º 31
0
        public OutlookClass()
        {
            try
            {
                //start outlook
                MyApp = new Application();
                MailNS = MyApp.GetNamespace("MAPI");

                string sProfile = "", sPassword="";

                bool bShowDialog = true, bNewSession=false;

                MailNS.Logon(sProfile, sPassword, bShowDialog, bNewSession);

                MyInbox = MailNS.GetDefaultFolder(OlDefaultFolders.olFolderInbox);

            }
            catch (System.Exception ex)
            {
                helpers.addLog("Exception: " + ex.Message);
            }
        }
Exemplo n.º 32
0
        /// <summary>
        /// code written by Joy
        /// excutes ansd the start the timer upload process when the backgoundworkers's do work event fires
        /// </summary>
        /// <param name="Item"></param>
        void doBackGroundUpload(object Item)
        {
            try
              {

              Globals.ThisAddIn.isTimerUploadRunning = true;
              OutlookObj = Globals.ThisAddIn.Application;
              outlookNameSpace = OutlookObj.GetNamespace("MAPI");
              Outlook.MAPIFolder oInBox = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
              Outlook.MAPIFolder olMailRootFolder = (Outlook.MAPIFolder)oInBox.Parent;
              oMailRootFolders = olMailRootFolder.Folders;
              Outlook.MailItem moveMail = (Outlook.MailItem)Item;
              string newCatName = "Successfully Uploaded";
              if (Globals.ThisAddIn.Application.Session.Categories[newCatName] == null)
              {
                  outlookNameSpace.Categories.Add(newCatName, Outlook.OlCategoryColor.olCategoryColorDarkGreen, Outlook.OlCategoryShortcutKey.olCategoryShortcutKeyNone);
              }

              XmlNode uploadFolderNode = UserLogManagerUtility.GetSPSiteURLDetails("", folderName);

              if (uploadFolderNode != null)
              {
                  bool isDroppedItemUplaoded = false;

                  addinExplorer = ThisAddIn.OutlookObj.ActiveExplorer();

                  //Check the folder mapping with documnet library

                  if (isUserDroppedItemsCanUpload == false)
                  {
                      //Show message
                      try
                      {

                          Outlook.MailItem m = (Outlook.MailItem)Item;
                          mailitemEntryID = m.EntryID;

                          try
                          {
                              mailitem = m;

                              mailitemEntryID = m.EntryID;

                              string strsubject = m.EntryID;
                              if (string.IsNullOrEmpty(strsubject))
                              {
                                  strsubject = "tempomailcopy";
                              }

                              mailitemEntryID = strsubject;

                              string tempFilePath = UserLogManagerUtility.RootDirectory + "\\" + strsubject + ".msg";

                              if (Directory.Exists(UserLogManagerUtility.RootDirectory) == false)
                              {
                                  Directory.CreateDirectory(UserLogManagerUtility.RootDirectory);
                              }
                              m.SaveAs(tempFilePath, Outlook.OlSaveAsType.olMSG);

                          }
                          catch (Exception ex)
                          {

                          }

                          Outlook.MAPIFolder fp = (Outlook.MAPIFolder)m.Parent;
                          DoNotMoveInNonDocLib(mailitemEntryID, fp);

                      }
                      catch (Exception)
                      {
                          NonDocMoveReportItem(Item);
                      }

                      MessageBox.Show("You are attempting to move files to a non document library. This action is not supported.", "ITOPIA", MessageBoxButtons.OK, MessageBoxIcon.Information);

                      return;

                  }

                  if (frmUploadItemsListObject == null || (frmUploadItemsListObject != null && frmUploadItemsListObject.IsDisposed == true))
                  {
                      //frmUploadItemsListObject = new frmUploadItemsList();

                      // myCustomTaskPane = Globals.ThisAddIn.CustomTaskPanes.Add(frmUploadItemsListObject, "ITOPIA");
                      //myCustomTaskPane.Visible = true;

                      IAddCustomTaskPane();

                  }
                  //frmUploadItemsListObject.TopLevel = true;
                  //frmUploadItemsListObject.TopMost = true;

                  ////////////////////// frmUploadItemsListObject.Show();

                  try
                  {

                      //////
                      //////////
                      Outlook.MailItem oMailItem = (Outlook.MailItem)Item;
                      parentfolder = (Outlook.MAPIFolder)oMailItem.Parent;
                      try
                      {
                          mailitem = oMailItem;

                          mailitemEntryID = oMailItem.EntryID;

                          string strsubject = oMailItem.EntryID;
                          if (string.IsNullOrEmpty(strsubject))
                          {
                              strsubject = "tempomailcopy";
                          }

                          mailitemEntryID = strsubject;

                          string tempFilePath = UserLogManagerUtility.RootDirectory + "\\" + strsubject + ".msg";

                          if (Directory.Exists(UserLogManagerUtility.RootDirectory) == false)
                          {
                              Directory.CreateDirectory(UserLogManagerUtility.RootDirectory);
                          }
                          oMailItem.SaveAs(tempFilePath, Outlook.OlSaveAsType.olMSG);

                      }
                      catch (Exception ex)
                      {

                      }

                      string fileName = string.Empty;
                      if (!string.IsNullOrEmpty(oMailItem.Subject))
                      {
                          //Replce any specila characters in subject
                          fileName = Regex.Replace(oMailItem.Subject, strMailSubjectReplcePattern, " ");
                          fileName = fileName.Replace(".", "_");
                      }

                      if (string.IsNullOrEmpty(fileName))
                      {
                          DateTime dtReceivedDate = Convert.ToDateTime(oMailItem.ReceivedTime);
                          fileName = "Untitled_" + dtReceivedDate.Day + "_" + dtReceivedDate.Month + "_" + dtReceivedDate.Year + "_" + dtReceivedDate.Hour + "_" + dtReceivedDate.Minute + "_" + dtReceivedDate.Millisecond;
                      }

                      UploadItemsData newUploadData = new UploadItemsData();
                      newUploadData.ElapsedTime = DateTime.Now;
                      newUploadData.UploadFileName = fileName;// oMailItem.Subject;
                      newUploadData.UploadFileExtension = ".msg";
                      newUploadData.UploadingMailItem = oMailItem;
                      newUploadData.UploadType = TypeOfUploading.Mail;
                      newUploadData.DisplayFolderName = folderName;
                      frmUploadItemsListObject.UploadUsingDelegate(newUploadData);
                      //Set dropped items is uploaded
                      /////////////////////////updated by Joy on 25.07.2012/////////////////////////////////
                      bool uploadStatus = frmUploadItemsListObject.IsSuccessfullyUploaded;
                      XMLLogOptions userOption = UserLogManagerUtility.GetUserConfigurationOptions();
                      if (uploadStatus == true)
                      {
                          // Globals.ThisAddIn.isTimerUploaded = true;
                          isDroppedItemUplaoded = true;

                          for (int i = 0; i <= activeDroppingFolder.Items.Count; i++)
                          {
                              try
                              {
                                  Outlook.MailItem me = (Outlook.MailItem)activeDroppingFolder.Items[i];

                                  if (me.EntryID == mailitemEntryID)
                                  {
                                      me.Categories.Remove(0);
                                      me.Categories = newCatName;
                                      me.Save();

                                      if (userOption.AutoDeleteEmails == true)
                                      {
                                          UserMailDeleteOption(mailitemEntryID, parentfolder);
                                      }
                                  }
                              }
                              catch (Exception ex)
                              {

                              }
                          }

                          frmUploadItemsListObject.lblPRStatus.Invoke(new updateProgresStatus(() =>
                          {
                              frmUploadItemsListObject.lblPRStatus.Text = Globals.ThisAddIn.no_of_t_item_uploaded.ToString() + " " + "of" + " " + Globals.ThisAddIn.no_of_pending_items_to_be_uploaded.ToString() + " " + "Uploaded";
                          }));
                          frmUploadItemsListObject.progressBar1.Invoke(new updateProgessBar(() =>
                          {
                              frmUploadItemsListObject.progressBar1.Value = (((Globals.ThisAddIn.no_of_t_item_uploaded * 100 / Globals.ThisAddIn.no_of_pending_items_to_be_uploaded)));
                          }));

                      }
                      else
                      {
                          isDroppedItemUplaoded = false;
                      }

                      /////////////////////////updated by Joy on 25.07.2012/////////////////////////////////
                  }
                  catch (Exception ex)
                  {
                      isDroppedItemUplaoded = MoveItemIsReportItem(Item);
                  }

                  try
                  {
                      if (isDroppedItemUplaoded == false)
                      {
                          //string tempName = oDocItem.Subject;
                          string tempName = string.Empty;
                          Outlook.DocumentItem oDocItem = (Outlook.DocumentItem)Item;

                          try
                          {

                              Outlook._MailItem myMailItem = (Outlook.MailItem)addinExplorer.Selection[1];
                              foreach (Outlook.Attachment oAttachment in myMailItem.Attachments)
                              {
                                  if (oAttachment.FileName == oDocItem.Subject)
                                  {
                                      tempName = oAttachment.FileName;
                                      tempName = tempName.Substring(tempName.LastIndexOf("."));
                                      oAttachment.SaveAsFile(UserLogManagerUtility.RootDirectory + @"\tempattachment" + tempName);

                                      //Read file data to bytes
                                      //byte[] fileBytes = File.ReadAllBytes(UserLogManagerUtility.RootDirectory + @"\tempattachment" + tempName);
                                      System.IO.FileStream Strm = new System.IO.FileStream(UserLogManagerUtility.RootDirectory + @"\tempattachment" + tempName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                                      System.IO.BinaryReader reader = new System.IO.BinaryReader(Strm);
                                      byte[] fileBytes = reader.ReadBytes(Convert.ToInt32(Strm.Length));
                                      reader.Close();
                                      Strm.Close();

                                      //Replace any special characters are there in file name
                                      string fileName = Regex.Replace(oAttachment.FileName, strAttachmentReplacePattern, " ");

                                      //Add uplaod attachment item data to from list.
                                      UploadItemsData newUploadData = new UploadItemsData();
                                      newUploadData.UploadType = TypeOfUploading.Attachment;
                                      newUploadData.AttachmentData = fileBytes;
                                      newUploadData.DisplayFolderName = activeDroppingFolder.Name;

                                      if (fileName.Contains("."))
                                      {
                                          newUploadData.UploadFileName = fileName.Substring(0, fileName.LastIndexOf("."));
                                          newUploadData.UploadFileExtension = fileName.Substring(fileName.LastIndexOf("."));

                                          if (string.IsNullOrEmpty(newUploadData.UploadFileName.Trim()))
                                          {
                                              //check file name conatins empty add the date time
                                              newUploadData.UploadFileName = "Untitled_" + DateTime.Now.ToFileTime();

                                          }
                                      }

                                      //Add to form
                                      frmUploadItemsListObject.UploadUsingDelegate(newUploadData);
                                      //Set dropped mail attachment items is uploaded.
                                      isDroppedItemUplaoded = true;
                                      newUploadData = null;
                                      //oDocItem.Delete();
                                      break;
                                  }
                              }
                          }
                          catch (InvalidCastException ex)
                          {
                              //Set dropped mail attachment items is uploaded to false
                              isDroppedItemUplaoded = false;
                          }

                          if (isDroppedItemUplaoded == false)
                          {
                              tempName = oDocItem.Subject;
                              tempName = tempName.Substring(tempName.LastIndexOf("."));
                              oDocItem.SaveAs(UserLogManagerUtility.RootDirectory + @"\tempattachment" + tempName, Type.Missing);

                              System.IO.FileStream Strm = new System.IO.FileStream(UserLogManagerUtility.RootDirectory + @"\tempattachment" + tempName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                              System.IO.BinaryReader reader = new System.IO.BinaryReader(Strm);
                              byte[] fileBytes = reader.ReadBytes(Convert.ToInt32(Strm.Length));
                              reader.Close();
                              Strm.Close();

                              //Replace any special characters are there in file name
                              string fileName = Regex.Replace(oDocItem.Subject, strAttachmentReplacePattern, " ");

                              //Add uplaod attachment item data to from list.
                              UploadItemsData newUploadData = new UploadItemsData();
                              newUploadData.UploadType = TypeOfUploading.Attachment;
                              newUploadData.AttachmentData = fileBytes;
                              newUploadData.DisplayFolderName = activeDroppingFolder.Name;

                              if (fileName.Contains("."))
                              {
                                  newUploadData.UploadFileName = fileName.Substring(0, fileName.LastIndexOf("."));
                                  newUploadData.UploadFileExtension = fileName.Substring(fileName.LastIndexOf("."));

                                  if (string.IsNullOrEmpty(newUploadData.UploadFileName.Trim()))
                                  {
                                      //check file name conatins empty add the date time
                                      newUploadData.UploadFileName = "Untitled_" + DateTime.Now.ToFileTime();

                                  }
                              }

                              //Add to form
                              frmUploadItemsListObject.UploadUsingDelegate(newUploadData);
                              newUploadData = null;
                              //oDocItem.Delete();
                          }

                      }
                  }
                  catch (Exception ex)
                  {
                      //throw ex;
                      //////////////////////////////updated by Joy on 28.07.2012///////////////////////////////////
                      //  EncodingAndDecoding.ShowMessageBox("FolderItem Add Event_DocItem Conv", ex.Message, MessageBoxIcon.Error);
                      //////////////////////////////updated by Joy on 28.07.2012///////////////////////////////////
                  }

                  try
                  {
                      XMLLogOptions userOptions = UserLogManagerUtility.GetUserConfigurationOptions();

                      for (int i = 0; i <= parentfolder.Items.Count; i++)
                      {
                          try
                          {
                              Outlook.MailItem me = (Outlook.MailItem)parentfolder.Items[i];

                              if (me.EntryID == mailitemEntryID)
                              {
                                  ///////////////////////////modified by Joy on 10.08.2012////////////////////////////////////

                                  if (isDroppedItemUplaoded == true)
                                  {

                                      me.Categories.Remove(0);
                                      me.Categories = newCatName;
                                      me.Save();
                                      if (userOptions.AutoDeleteEmails == true)
                                      {
                                          UserMailDeleteOption(mailitemEntryID, parentfolder);
                                      }
                                      //parentfolder.Items.Remove(i);
                                  }
                                  ///////////////////////////modified by Joy on 10.08.2012////////////////////////////////////

                              }
                          }
                          catch (Exception)
                          {

                          }
                      }
                  }

                  catch (Exception)
                  {

                  }
                  if (!string.IsNullOrEmpty(mailitemEntryID))
                  {
                      if (ItemType == TypeOfMailItem.ReportItem)
                      {
                          UserReportItemDeleteOption(mailitemEntryID, parentfolder);
                      }
                      else
                      {
                          ///////////////////////////Updated by Joy on 16.08.2012....to be updated later///////////////////////////////
                          // UserMailDeleteOption(mailitemEntryID, parentfolder);
                          ///////////////////////////Updated by Joy on 16.08.2012....to be updated later///////////////////////////////
                      }
                  }

              }

              }
              catch (Exception ex)
              {
              EncodingAndDecoding.ShowMessageBox("Folder Item Add Event", ex.Message, MessageBoxIcon.Error);

              }

              //AddToUploadList(Item);
        }
        private void ThisAddIn_Startup(object sender, EventArgs e)
        {
            //Executive flag addin
            _outlookNameSpace = Application.GetNamespace("MAPI");
            _inbox = _outlookNameSpace.GetDefaultFolder(
                Outlook.OlDefaultFolders.olFolderInbox);

            //Generate contacts from email I have received from capSpire
            _contacts = _outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
            _items = _inbox.Items;
            _items.ItemAdd +=
                items_ItemAdd;
            AddContactsToItems();

            _selectExplorers = Application.Explorers;
            _selectExplorers.NewExplorer += newExplorer_Event;
            AddToolbar();
        }
Exemplo n.º 34
0
        /// <summary>
        ///<c>ThisAddIn_Startup</c>  Outlook startup event
        /// This Event is  executed when outlook starts(outlook is opened)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            try
            {

                //declare and initialize variables used for the Instant PLUS check
                Int32 result = 0;

                string filePath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\ITOPIA\\SharePoint Link 2010\\", "SharePoint Link.xml");

                //Make the call to Instant PLUS and store the result
                result = Ip2LibManaged.CallInstantPLUS(Ip2LibManaged.FLAGS_NONE, "30820274020100300D06092A864886F70D01010105000482025E3082025A02010002818100BA81817A32C249909671428137ECFC2AEF45E5F746C218550C2191F525A15E65DCD87CAD8B46EB870E55897D1D185B9D88BCDDB6D44CB8B9DDFD7DB4948E8CF91743377F31DB733438828CA0EC3176D8650C8F4B77578E60285F55049D9A707C61FF75C7C626492415BBCBE8058E4F220826A356F1C50B29C92B354C61BEF21F0201110281800AF88F254E47A9F97242E5CB5DA4874DD1D6EF68E60B6AD7D389810E6BA0149C94853482ADD6FECBB58C8F9DF2A71472ADB0C1BF75E665381C1DF855EA9EF93BBA5432731B506EDFE944C217EB09F27AA8203C7D7310D78995A9549690836B313CDCD0B2FA6AD79576977EB44B33D46577E9EA6939DCF8388761E25C3FADF9B1024100F3F70346EEA01874427576DFF5136A9B3A1AB4522ADD2073669376540C6CE65A1A613D0F4754FAD4C8DA70D3F5F5F0D4DAF97B0CF49D9BDA0ECE0F8F46A19BBF024100C3B4DA9372E3FDE1787C322A5B74F21800CDD6A4A85C1DC9D18D40B0F8736BDD3CF45CD5DDB8FD626CD1F11B1127439036A4974D257AF38EBCDD1D9CE08FC1A1024100AC35E43211DA6B9D5C16AE43BC0DB4A9CEA9703A00239E6F93B36295AE6AFCF44EDB3A28E70ECF2CCA039AEFF8E9D72CD6CE38BDD9D8AA3F91FADDCE8C35D75902405095C369E40386A8228D7E1170F3EB370F63D0DA63713971382B1AA3392077B57373ADC1796A4A3796385438525B762C52BC3E4CF150BEA42FA6577CD4EFE65102405162E2024CE04279E92731B490BE2431758FA6D032B0DB85B2AC782956832095800B4A8AB7D6FC1DB905CA38508FC3CC49994A48940CF9BB5761C07A9289D492", filePath);

                if (11574 != result)
                {
                    //this.Close();
                    //this.Application.ActiveExplorer().Close();
                    //this.Application.Quit();
                    return;
                }

                isAuthorized = true;

                #region Add-in Express Regions generated code - do not modify
                this.FormsManager = AddinExpress.OL.ADXOlFormsManager.CurrentInstance;
                this.FormsManager.OnInitialize +=
                    new AddinExpress.OL.ADXOlFormsManager.OnComponentInitialize_EventHandler(this.FormsManager_OnInitialize);
                //this.FormsManager.ADXBeforeFolderSwitchEx +=
                //     new AddinExpress.OL.ADXOlFormsManager.BeforeFolderSwitchEx_EventHandler(FormsManager_ADXBeforeFolderSwitchEx);

                this.FormsManager.Initialize(this);
                #endregion

                //DateTime dtExpiredDate = new DateTime(2010, 08, 05);
                //DateTime dtWorkingDate = DateTime.Now;
                //TimeSpan t = new TimeSpan();
                //t = dtExpiredDate.Subtract(dtWorkingDate);

                //if (t.Days < 30 && t.Days >= 0)
                //{

                //outlookObj = new Outlook.Application();

                OutlookObj = Globals.ThisAddIn.Application;
                //Gte MAPI Name space
                outlookNameSpace = OutlookObj.GetNamespace("MAPI");

                //Get inbox folder
                Outlook.MAPIFolder oInBox = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                //Get current user details to save the xml file based on user
                string userName = outlookNameSpace.DefaultStore.DisplayName;
                userName = userName.Replace("-", "_");
                userName = userName.Replace(" ", "");
                UserLogManagerUtility.UserXMLFileName = userName;

                //Get parent root folder
                Outlook.MAPIFolder olMailRootFolder = (Outlook.MAPIFolder)oInBox.Parent;
                //Get all folder
                oMailRootFolders = olMailRootFolder.Folders;
                //Create folder remove event
                oMailRootFolders.FolderRemove += new Microsoft.Office.Interop.Outlook.FoldersEvents_FolderRemoveEventHandler(oMailRootFolders_FolderRemove);

                //Set inbox folder as default

                try
                {

                    OutlookObj.ActiveExplorer().CurrentFolder = oInBox;
                    addinExplorer = this.Application.ActiveExplorer();
                    addinExplorer.BeforeItemPaste += new Microsoft.Office.Interop.Outlook.ExplorerEvents_10_BeforeItemPasteEventHandler(addinExplorer_BeforeItemPaste);
                    //Create folder Switch event
                    addinExplorer.FolderSwitch += new Microsoft.Office.Interop.Outlook.ExplorerEvents_10_FolderSwitchEventHandler(addinExplorer_FolderSwitch);

                    //crete folder context menu disply
                    this.Application.FolderContextMenuDisplay += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_FolderContextMenuDisplayEventHandler(Application_FolderContextMenuDisplay);

                    this.Application.ContextMenuClose += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_ContextMenuCloseEventHandler(Application_ContextMenuClose);

                    strParentMenuTag = strParentMenuName;
                    // Removing the Existing Menu Bar
                    //  RemoveItopiaMenuBarIfExists(strParentMenuTag);
                    // Adding The Menu Bar Freshly
                    //  CreateParentMenu(strParentMenuTag, strParentMenuName);
                    myTargetFolder = oInBox;
                    CreateAddEventOnFolders();
                    //CreateDefaultAddEventOnFolders();
                    //Create outlook explorer wrapper class
                    OutlookWindow = new OutlookExplorerWrapper(OutlookObj.ActiveExplorer());
                    OutlookWindow.Close += new EventHandler(OutlookWindow_Close);

                    ((Outlook.ExplorerEvents_Event)addinExplorer).BeforeFolderSwitch += new Microsoft.Office.Interop.Outlook.ExplorerEvents_BeforeFolderSwitchEventHandler(ThisAddIn_BeforeFolderSwitch);

                    oMailRootFolders.FolderChange += new Outlook.FoldersEvents_FolderChangeEventHandler(oMailRootFolders_FolderChange);

                    foreach (Outlook.MAPIFolder item in oMailRootFolders)
                    {

                        try
                        {
                            item.Folders.FolderChange -= new Outlook.FoldersEvents_FolderChangeEventHandler(oMailRootFolders_FolderChange);

                        }
                        catch (Exception)
                        {
                        }
                        item.Folders.FolderChange += new Outlook.FoldersEvents_FolderChangeEventHandler(oMailRootFolders_FolderChange);

                    }

                    Outlook.Items activeDroppingFolderItems;

                    activeDroppingFolderItems = oInBox.Items;

                    userOptions = UserLogManagerUtility.GetUserConfigurationOptions();
                    currentFolderSelected = oInBox.Name;
                    currentFolderSelectedGuid = oInBox.EntryID;
                }
                catch (Exception ex)
                {
                    ListWebClass.Log(ex.Message, true);
                }

                // }

            }
            catch (Exception ex)
            {
                EncodingAndDecoding.ShowMessageBox("StartUP", ex.Message, MessageBoxIcon.Error);
            }

            /// <summary>
            //code written by Joy
            ///initializes the object of timer
            /// </summary>

            System.Threading.AutoResetEvent reset = new System.Threading.AutoResetEvent(true);

            timer = new System.Threading.Timer(new System.Threading.TimerCallback(doBackgroundUploading), reset, 180000, 180000);

            GC.KeepAlive(timer);
            form = new Form();
            form.Opacity = 0.01;
            form.Show();
            form.Visible = false;
        }
        /// <summary>
        /// ctor
        /// </summary>
        /// <exception cref="System.Runtime.InteropServices.COMException"/>
        public OutlookManager()
        {
            var current = System.Security.Principal.WindowsIdentity.GetCurrent();
            m_impContext = current.Impersonate();

            System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("OUTLOOK");
            int collCount = processes.Length;

            if (collCount != 0)
            {
                #region comment
                //try
                //{
                //    // create an application instance of Outlook
                //    oApp = new Microsoft.Office.Interop.Outlook.Application();
                //}
                //catch (System.Exception ex)
                //{
                //    try
                //    {
                //        // get Outlook in another way
                //        oApp = Marshal.GetActiveObject("Outlook.Application") as Microsoft.Office.Interop.Outlook.Application;
                //    }
                //    catch (System.Exception ex2)
                //    {
                //        // try some other way to get the object
                //        oApp = Activator.CreateInstance(Type.GetTypeFromProgID("Outlook.Application")) as Microsoft.Office.Interop.Outlook.Application;
                //    }
                //}
                #endregion

                try
                {
                    // Outlook already running, hook into the Outlook instance
                    m_outlookApp = System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application") as Microsoft.Office.Interop.Outlook.Application;
                }
                catch (System.Runtime.InteropServices.COMException ex)
                {
                    if (ex.ErrorCode == -2147221021)
                        m_outlookApp = new Application();
                    else
                        throw;
                }
            }
            else
                m_outlookApp = new Microsoft.Office.Interop.Outlook.Application();

            m_outNameSpace = m_outlookApp.GetNamespace("MAPI");
            m_allFolders = m_outNameSpace.Folders;

            m_outlookApp.NewMailEx += new ApplicationEvents_11_NewMailExEventHandler(outLookApp_NewMailEx);

            this.FoldersInOutlook = new List<string>();

            m_inboxFolder = m_outNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
            m_FoldersToMonitor = new List<string>();
            m_foldToMonitorInstances = new Dictionary<string, MAPIFolder>(StringComparer.OrdinalIgnoreCase);

            MAPIFolder mUserFolder = m_inboxFolder.Parent;
            if (mUserFolder != null)
            {
                foreach (object folder in mUserFolder.Folders)
                {
                    MAPIFolder mapiFolder = folder as MAPIFolder;
                    if (mapiFolder != null)
                    {
                        this.FoldersInOutlook.Add(mapiFolder.Name);
                    }
                }
            }
        }
Exemplo n.º 36
0
        /// <summary>
        /// <c>ReConnection</c> member function
        /// this function recreates the deleted  folder in outlook 
        /// </summary>
        /// <param name="xLogProperties"></param>
        /// <param name="parentfolder"></param>
        /// <returns></returns>
        public bool ReConnection(XMLLogProperties xLogProperties, Outlook.MAPIFolder parentfolder)
        {
            bool result = false;
            try
            {

                Outlook.MAPIFolder newFolder = null;
                ////////////////////////updated by Joy on 25.07.2012/////////////////
                Outlook.MAPIFolder newBrokenUploadsFolder = null;
                ////////////////////////updated by Joy on 25.07.2012/////////////////
                //outlookObj = new Outlook.Application();
                OutlookObj = Globals.ThisAddIn.Application;

                //Gte MAPI Name space
                outlookNameSpace = OutlookObj.GetNamespace("MAPI");
                Outlook.MAPIFolder olInboxFolder = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);

                Outlook.MAPIFolder Target = parentfolder;

                bool created = CreateFolderInOutLookSideMenu(xLogProperties.DisplayFolderName, xLogProperties.SiteURL, out newFolder, Target);

                if (created == true && newFolder != null)
                {

                    //Set new folder location
                    xLogProperties.OutlookFolderLocation = newFolder.FolderPath;
                    //Create node in xml file
                    //  UserLogManagerUtility.CreateXMLFileForStoringUserCredentials(xLogProperties);

                    MAPIFolderWrapper omapi = null;
                    if (string.IsNullOrEmpty(xLogProperties.DocumentLibraryName) == true)
                    {
                        //Doc name is empty means Folder is not mapped with Doc Lib
                        omapi = new MAPIFolderWrapper(ref  newFolder, addinExplorer, false);
                    }
                    else
                    {
                        omapi = new MAPIFolderWrapper(ref newFolder, addinExplorer, true);
                    }

                    newFolders.Add(omapi);

                }

            }
            catch (Exception ex)
            {

            }
            return result;
        }
Exemplo n.º 37
0
        /// <summary>
        /// code written by Joy
        /// moves or copies mail items to the selected mapped folder
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (this.ValidateChildren() == true)
            {
                if (ThisAddIn.IsUploadingFormIsOpen == true)
                {
                    if (Globals.ThisAddIn.frmlistObject != null)
                    {
                        Globals.ThisAddIn.frmlistObject.progressBar1.Value = Globals.ThisAddIn.frmlistObject.progressBar1.Minimum;
                        Globals.ThisAddIn.frmlistObject.lblPRStatus.Text = "";
                    }

                }
                string selected_mapiFolderName = cmbOptions.Text;
                this.Close();
                if (Globals.ThisAddIn.copy_button_clicked == true)
                {
                    OutlookObj = Globals.ThisAddIn.Application;
                    outlookNameSpace = OutlookObj.GetNamespace("MAPI");
                    olInBox = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                    parentFolder = (Microsoft.Office.Interop.Outlook.MAPIFolder)olInBox.Parent;
                    string mappedFolderName = cmbOptions.SelectedItem.ToString();
                    mappedFolder = MAPIFolderWrapper.GetFolder(parentFolder, mappedFolderName);
                    Outlook.MailItem mItem;
                    Outlook.MailItem copyMail;
                    Globals.ThisAddIn.isCopyRunninng = true;
                    foreach (Object obj in Globals.ThisAddIn.copySelected)
                    {
                        if (obj is Outlook.MailItem)
                        {
                            mItem = (Outlook.MailItem)obj;
                            copyMail = mItem.Copy() as Outlook.MailItem;
                            copyMail.Move(mappedFolder);
                            //doBackGroundUpload(mItem);
                        }
                    }
                }
                else if (Globals.ThisAddIn.move_button_clicked == true)
                {

                        OutlookObj = Globals.ThisAddIn.Application;
                        outlookNameSpace = OutlookObj.GetNamespace("MAPI");
                        olInBox = outlookNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                        parentFolder = (Microsoft.Office.Interop.Outlook.MAPIFolder)olInBox.Parent;
                        string mappedFolderName = cmbOptions.SelectedItem.ToString();
                        mappedFolder = MAPIFolderWrapper.GetFolder(parentFolder, mappedFolderName);
                        Outlook.MailItem mItem;
                        Globals.ThisAddIn.isMoveRunning = true;
                        foreach (Object obj in Globals.ThisAddIn.moveSelected)
                        {
                            if (obj is Outlook.MailItem)
                            {
                                mItem = (Outlook.MailItem)obj;
                                mItem.Move(mappedFolder);
                                //doBackGroundUpload(mItem);
                            }
                        }

                }
            }
            else
                return;
        }
Exemplo n.º 38
0
        /// <summary>
        /// Initializes the OutLook application and retrieves the meetings scheduled for current day.
        /// For logging into OutLook, we need the profile name. Default profile name is extracted from registry settings.
        /// </summary>
        private void InitializeMeetingDuration()
        {
            try
            {
                if (!Process.GetProcessesByName("OUTLOOK").Any())
                    return;
                outlookApplication = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
                nameSpace = outlookApplication.GetNamespace("mapi");
                var profile = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles", "DefaultProfile", null);
                nameSpace.Logon(profile.ToString(), Missing.Value, true, true);
                fldCalander =
                    nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar) as Outlook.Folder;
                fldDeletedItems = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDeletedItems) as Outlook.Folder;
                items = GetAppointmentsInRange(fldCalander);

                fldCalander.BeforeItemMove += fldCalander_BeforeItemMove;
                items.ItemAdd += Items_ItemAdd;
                items.ItemChange += Items_ItemChange;

                if (items != null)
                {
                    foreach (Outlook.AppointmentItem oAppt in items)
                    {
                        meetings.Add(oAppt.GlobalAppointmentID,
                            new MeetingDetails(oAppt.Start, oAppt.End, oAppt.Duration));
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.ToString());
            }
        }
Exemplo n.º 39
0
        //Method that runs when the plugin loads
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            //Prompt to run application, and start and end timer
            System.Windows.Forms.DialogResult result = System.Windows.Forms.MessageBox.Show("Do you want to run SigX?", "Hit yes, I'll be quick", System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
            if (result == DialogResult.Yes)
            {
                timer = Stopwatch.StartNew(); ReadMail();  //Start stopwatch and run batch parsing function
            }
            //Configure plugin to run when email is added to Inbox
            outlookNameSpace = this.Application.GetNamespace("MAPI");
            inbox = outlookNameSpace.GetDefaultFolder(
                    Microsoft.Office.Interop.Outlook.
                    OlDefaultFolders.olFolderInbox);
            items = inbox.Items;

            items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(ReadSingleMail); // Modified method to run for single email
        }
Exemplo n.º 40
0
        /// <summary>
        /// Fetch amount of time spent in minutes for todays date
        /// </summary>
        /// <returns></returns>
        public static double GetMeetingDuration()
        {
            Outlook.NameSpace nameSpace;
            Outlook.Application outlookApplication;
            Outlook.Folder fldCalander;
            double meetingMinutes = 0;

            try
            {
                outlookApplication = new Outlook.Application();
                nameSpace = outlookApplication.GetNamespace("mapi");
                var profile = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles", "DefaultProfile", null);
                nameSpace.Logon(profile, Missing.Value, true, true);
                fldCalander =
                    nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar) as Outlook.Folder;
                Outlook.Items items = GetAppointmentsInRange(fldCalander);

                if (items != null)
                {
                    foreach (Outlook.AppointmentItem oAppt in items)
                    {
                        meetingMinutes += (oAppt.End - oAppt.Start).TotalMinutes;
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                fldCalander = null;
                nameSpace = null;
            }

            return meetingMinutes;
        }
Exemplo n.º 41
0
        /// <summary>
        /// Initalizes and logs into an Outlook session. Must call this 
        /// before using any of the other methods of this class.
        /// </summary>
        public void Initialize()
        {
            if (_isInitialized)
            {
                // Already initialized. Return silently.
                return;
            }

            _olNS = _olApp.GetNamespace("MAPI");

            _olNS.Logon(Missing.Value, Missing.Value, Missing.Value, true);

            _olContactsFolder = _olNS.GetDefaultFolder(
                Outlook.OlDefaultFolders.olFolderContacts);

            _isInitialized = true;
        }
Exemplo n.º 42
0
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            RemoveMenubar();
            AddMenuBar();

            outlookNamespace = this.Application.GetNamespace("MAPI");
            inbox = outlookNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);

            outlookItems = inbox.Items;
            outlookItems.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(items_ItemAdd);
        }
Exemplo n.º 43
-1
		public OutlookDataSource(IHostApplicationProvider hostAppProvider, IMail mailItem)
		{
			_mailItem = mailItem;
			Logger.LogInfo("OutlookSentItemSource.OutlookDataSource()");

			_ns = hostAppProvider.Host.GetNamespace("MAPI");
			_sent = _ns.GetDefaultFolder(MsOutlook.OlDefaultFolders.olFolderSentMail);

			_items = _sent.Items;
		}