Ejemplo n.º 1
0
        protected static Outlook.Application GetApplicationObject()
        {
            Outlook.Application application = null;

            // Check whether there is an Outlook process running.
            if (Process.GetProcessesByName("OUTLOOK").Any())
            {
                try
                {
                    // If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
                    application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
                }
                catch (Exception)
                {
                    return(null);
                }
            }
            else
            {
                return(null);

                // If not, create a new instance of Outlook and log on to the default profile.
                application = new Outlook.Application();
                Outlook.NameSpace nameSpace = application.GetNamespace("MAPI");
                nameSpace.Logon("", "", Missing.Value, Missing.Value);
                nameSpace = null;
            }

            // Return the Outlook Application object.
            return(application);
        }
Ejemplo n.º 2
0
        static void Main(string[] args)
        {
            Outlook.Application OutlookApp = null;
            if (System.Diagnostics.Process.GetProcessesByName("OUTLOOK").Length > 0)
            {
                // If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
                OutlookApp = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
            }
            else
            {
                // If not, create a new instance of Outlook and log on to the default profile.
                OutlookApp = new Outlook.Application();
            }

            string defaultProfile = OutlookApp.DefaultProfileName;

            Outlook.NameSpace nameSpace = OutlookApp.GetNamespace("MAPI");
            nameSpace.Logon(Profile: "", Password: "", ShowDialog: Missing.Value, NewSession: Missing.Value);
            var    OutlookSession = OutlookApp.Session;
            Stores stores         = nameSpace.Stores;

            //Task.Factory.StartNew(() => EnumerateFolderItems(stores, "2007-00-00", "2007-00-00"));
            EnumerateFolderItems(stores, "2007-00-00", "2007-00-00");
            //EnumerateStores(stores);
            //DeleteEmptyFolders(stores);
            //for (int i = 0; i < 10; i++)
            //{
            //	EnumerateItems(stores);
            //}
            DeleteEmptyFolders(stores);

            //CreateSortStores(OutlookApp);
            //NameSortStores(OutlookApp);
        }
Ejemplo n.º 3
0
		public void TestFixtureSetUp()
		{
			_sender = new EmailSender();
			_app = _sender.Initialise();
			_outlookSession = _app.Session;
			_outlookSession.Logon("Outlook", "", false, true);
		}
Ejemplo n.º 4
0
        /* void CreateNewMail()
         * Init parameters, prepare to send a new mail.
         */
        private void CreateNewMail()
        {
            try
            {
                if (this._serverType == MailServerType.SMTP)
                {
                    _netMail = new MailMessage();

                    _netMail.IsBodyHtml = _mailType == MailType.HTML;

                    if (_smtpServer == null)
                    {
                        _smtpServer = new SmtpClient(_smtpServerAddr);
                    }
                }
                else
                {
#if OUTLOOK
                    if (!_logged)
                    {
                        _oNS.Logon(null, null, false, false);
                        _logged = true;
                    }

                    _oMsg = (Outlook.MailItem)_oApp.CreateItem(Outlook.OlItemType.olMailItem);
#endif
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Can not create a new mail: " + ex.ToString());
            }
        }
Ejemplo n.º 5
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();
        }
Ejemplo n.º 6
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());
            }
        }
        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);
        }
Ejemplo n.º 8
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);
        }
Ejemplo n.º 9
0
        private void btnFolderSelect_Click(object sender, EventArgs e)
        {
            object missing = Missing.Value;

            //get the Outlook Application Object
            Outlook.Application outlookApplication = new Outlook.Application();

            //get the namespace object
            Outlook.NameSpace nameSpace = outlookApplication.GetNamespace("MAPI");

            //Logon to Session, here we use an already opened Outlook session
            nameSpace.Logon(missing, missing, false, false);

            //get the InboxFolder
            Outlook.MAPIFolder Folder = nameSpace.PickFolder();
            if (Folder != null)
            {
                txtMoveToFolder.Text           = Folder.Name;
                this.Profile.MoveFolderName    = Folder.EntryID;
                this.Profile.MoveFolderStoreId = Folder.StoreID;
            }

            //release used resources
            if (Folder != null)
            {
                Marshal.ReleaseComObject(Folder);
            }

            //logof from namespace
            nameSpace.Logoff();

            //release resources
            Marshal.ReleaseComObject(nameSpace);
            Marshal.ReleaseComObject(outlookApplication.Application);
        }
        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();
        }
Ejemplo n.º 11
0
 public WHSMailService()
 {
     // get an instance of the MAPI namespace and login
     Outlook.Application app = new Outlook.ApplicationClass();
     _nameSpace = app.GetNamespace("MAPI");
     _nameSpace.Logon(null, null, false, false);
 }
Ejemplo n.º 12
0
        private void btnSync_Click(object sender, System.EventArgs e)
        {
            //try
            //{
            btnSync.Enabled = false;
            this.Cursor     = Cursors.WaitCursor;

            sbStatus.Text = "Connecting to Outlook...";
            Application.DoEvents();

            //Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.ApplicationClass();
            Outlook.Application oApp = new Outlook.Application();
            Outlook.NameSpace   oNS  = oApp.GetNamespace("mapi");
            oNS.Logon("Outlook", Missing.Value, false, true);

            Outlook.MAPIFolder oContacts = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);
            Outlook.Items      oItems    = oContacts.Items;

            if (cbStaff.Checked)
            {
                PersonCollection staff = new PersonCollection();
                staff.LoadStaffMembers();
                SyncPeople(oApp, oItems, "Staff", staff);
            }

            foreach (Object pItem in clbTags.CheckedItems)
            {
                Profile profile = new Profile(((CheckItem)pItem).ID);
                SyncPeople(oApp, oItems, profile.Title, profile.Members);
                SyncChildProfiles(oApp, oItems, profile, true);
            }
            oNS.Logoff();

            oApp   = null;
            oNS    = null;
            oItems = null;

            this.Cursor = Cursors.Default;
            MessageBox.Show("Outlook contacts have been updated", "Import Completed", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //}
            //catch(System.Exception ex)
            //{
            //    this.Cursor = Cursors.Default;
            //    MessageBox.Show("An error occurred while updating your contacts:\n\n" + ex.Message, "Import Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}

            //finally
            //{
            //}

            sbStatus.Text = string.Empty;
            setButtonEnabled();
            if (cbClose.Checked)
            {
                this.Close();
            }
        }
Ejemplo n.º 13
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                // Create the Outlook Application
                Outlook.Application oApp = new Outlook.Application();
                // Create NameSpace
                Outlook.NameSpace oNS = (Outlook.NameSpace)oApp.GetNamespace("MAPI");
                oNS.Logon(null, null, false, false);
                // Get DDS Service Desk Calendar
                Outlook.MAPIFolder oFolder;
                Outlook.Recipient  oRecipient;
                string             calendarName = "*****@*****.**";


                // Create a new appointment item
                Outlook.AppointmentItem oMsg = (Outlook.AppointmentItem)oApp.CreateItem(Outlook.OlItemType.olAppointmentItem);
                // Set Recipients
                oRecipient = oNS.CreateRecipient(calendarName);
                oRecipient.Resolve();
                oFolder = oNS.GetSharedDefaultFolder(oRecipient, Outlook.OlDefaultFolders.olFolderCalendar);
                // Set Appointment Start Time and End Time
                oMsg       = oFolder.Items.Add("IPM.Appointment") as Outlook.AppointmentItem;
                oMsg.Start = DateTime.Parse(dateTimePicker1.Text + " " + comboBox1.Text);
                oMsg.End   = DateTime.Parse(dateTimePicker2.Text + " " + comboBox2.Text);
                //Set the Body
                string message = "The Below Is Information Regarding The IT Equipment Reservation" + Environment.NewLine;
                oMsg.Body = "The Below Is Information Regarding The IT Equipment Reservation" + Environment.NewLine + Environment.NewLine +
                            "Requester Information:" + Environment.NewLine +
                            "Email:" + " " + textBox1.Text + Environment.NewLine +
                            "First Name:" + " " + textBox2.Text + Environment.NewLine +
                            "Last Name:" + " " + textBox3.Text + Environment.NewLine + Environment.NewLine +
                            "Reservation Information:" + Environment.NewLine +
                            "Pick-Up Time:" + " " + comboBox1.Text + " " + "to" + " " + comboBox2.Text + Environment.NewLine +
                            "Pick-Up Date:" + " " + dateTimePicker1.Text + " " + "to" + " " + dateTimePicker2.Text + Environment.NewLine +
                            "Service Request Number:" + " " + textBox8.Text + Environment.NewLine + Environment.NewLine +
                            "Service Request Link:" + " " + "http://oasis.dds.ca.gov/applications/ISDRequests_Staff/index.cfm?pageAction=ShowDetail&RequestNum=" + textBox8.Text + Environment.NewLine +
                            "Reserved By Technician:" + Environment.NewLine +
                            "Email:" + " " + textBox4.Text + Environment.NewLine +
                            "First Name:" + " " + textBox5.Text + Environment.NewLine +
                            "Last Name:" + " " + textBox6.Text + Environment.NewLine +
                            "Telephone Number:" + " " + textBox7.Text + Environment.NewLine + Environment.NewLine +
                            "Comments" + Environment.NewLine +
                            richTextBox1.Text;
                //Set the Subject
                oMsg.Subject = "SR #" + " " + textBox8.Text + " " + textBox2.Text + " " + textBox3.Text + "-" + " Pick Up" + " " + textBox9.Text;
                //Set the location
                oMsg.Location = "DDS Service Desk -- HQ";
                //save the appointment
                oMsg.Save();
                //Show Confirmation Message
                MessageBox.Show("Successful");
            }
            catch (System.Exception ex)
            {
            }
        }
Ejemplo n.º 14
0
        public void LoginToOutlook()
        {
            if (_outlookApp == null)
            {
                _outlookApp = new Outlook.Application();

                _outlookNamespace = _outlookApp.GetNamespace("mapi");
            }
            /// TODO: RedemptioN?
            _outlookNamespace.Logon("Outlook", null, true, false);
        }
        static void Main(string[] args)
        {
            Outlook.Application oApp = new Outlook.Application();
            Outlook.NameSpace   oNS  = oApp.GetNamespace("mapi");
            oNS.Logon("appsystemacc", "App@12345", false, false);
            // this is how you set those properties from the session
            var EntryID = oApp.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox).EntryID;
            var StoreID = oApp.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox).StoreID;

            var folderID = oNS.GetFolderFromID(EntryID, StoreID);
        }
Ejemplo n.º 16
0
        //Outlook.MAPIFolder oRoot;

        public Form1()
        {
            // Windows Form 디자이너 지원에 필요합니다.
            InitializeComponent();

            // TODO: InitializeComponent를 호출한 다음 생성자 코드를 추가합니다.

            oApp = new Outlook.Application();
            oNS  = oApp.GetNamespace("mapi");
            oNS.Logon(Missing.Value, Missing.Value, false, true);
        }
Ejemplo n.º 17
0
 static void Main(string[] args)
 {
     Console.WriteLine("Hit enter key to start.");
     while (Console.ReadKey().Key != ConsoleKey.Enter)
     {
     }
     outlook = new Outlook.Application();
     Outlook.NameSpace nameSpace = outlook.GetNamespace("MAPI");
     try {
         nameSpace.Logon("", "", Missing.Value, Missing.Value);
         for (int i = 1; i <= totalMailCount; i++)
         {
             Outlook.MailItem mail = CreateMail(i, null, recipients[i % recipients.Length]);
             int mod = totalMailCount / attachmentCount;
             if (mod > 0 && i % mod == 0)
             {
                 mail.Attachments.Add(attachmentPath, Outlook.OlAttachmentType.olByValue, 1, attachmentPath);
             }
             mail.Send();
             if (i % progressMessageInterval == 0)
             {
                 Console.WriteLine(string.Format("{0} messages queued in outbox.", i));
             }
         }
     } catch (Exception ex) {
         Console.WriteLine(ex.Message);
         if (ex.InnerException != null)
         {
             Console.WriteLine(ex.InnerException.Message);
         }
         Console.WriteLine(ex.StackTrace);
     } finally {
         Console.WriteLine("Queuing finished.");
         Outlook.Folder outbox = nameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderOutbox) as Outlook.Folder;
         while (true)
         {
             int itemCount = outbox.Items.Count;
             if (itemCount == 0)
             {
                 break;
             }
             Console.WriteLine("{0} messages left in outbox. Wait until all messages flushed from outbox.", itemCount);
             Thread.Sleep(10000);
         }
         Console.WriteLine("All messages has been sent.");
         Console.WriteLine("Hit enter key to quit.");
         while (Console.ReadKey().Key != ConsoleKey.Enter)
         {
         }
         nameSpace.Logoff();
         outlook.Quit();
     }
 }
Ejemplo n.º 18
0
        private void DownloadAttachment()
        {
            try
            {
                string FilePath = @"C:\somefolder\", FileNamewithPath = null, Subj = "ProddowsFolder Test";
                Outlook.Application OApp       = new Outlook.Application();
                Outlook.NameSpace   ONameSpace = OApp.GetNamespace("MAPI");
                //Outlook.MailItem OMail = null;
                Outlook.MAPIFolder InboxFolder, ProddowsFolder, ProddowsLoadedFolder = null;
                ArrayList          MailCollection = new ArrayList();
                ONameSpace.Logon("group/user", null, false, true);
                InboxFolder    = ONameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
                ProddowsFolder = InboxFolder.Folders["Proddows"];

                //for (int j = 0; j <= InboxFolder.Folders.Count; j++ )
                //{
                //    MessageBox.Show("Name: " + InboxFolder.Folders.Parent + " FolderPath: " + InboxFolder.FolderPath);
                //}

                ProddowsLoadedFolder = ProddowsFolder.Folders["Downloaded"];
                Outlook.Items OItem = InboxFolder.Items;

                foreach (Outlook.MailItem item in ProddowsFolder.Items)
                {
                    if (item != null && item.Subject == Subj)
                    {
                        MailCollection.Add(item);
                    }
                }

                foreach (Outlook.MailItem OMItem in MailCollection)
                {
                    foreach (Outlook.Attachment OAttactment in OMItem.Attachments)
                    {
                        FileNamewithPath = FilePath + OAttactment.FileName;
                        OAttactment.SaveAsFile(FileNamewithPath);

                        OMItem.Move(ProddowsLoadedFolder);
                    }
                }
                ONameSpace.Logoff();
                OItem          = null;
                MailCollection = null;
                ONameSpace     = null;
                OApp           = null;
            }
            catch (Exception e)
            {
            }
        }
Ejemplo n.º 19
0
		public void TestFixtureSetUp()
		{
			m_sender = new EmailSender();

			m_app = m_sender.Initialise();

			m_outlookSession = m_app.Session as Outlook.NameSpace;
			m_outlookSession.Logon("Outlook", "", false, true);
#if DEBUG
			m_manifestPath = Workshare.TestUtils.TestFileUtils.MakeRootPathAbsolute(@"\Win32\debug\Workshare.RegFreeCom.manifest");
#else
			m_manifestPath = Workshare.TestUtils.TestFileUtils.MakeRootPathAbsolute(@"\Win32\release\Workshare.RegFreeCom.manifest");
#endif

		}
Ejemplo n.º 20
0
        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();
        }
Ejemplo n.º 21
0
        private void button1_Click(object sender, EventArgs e)
        {
            Outlook.Application olApp  = new Outlook.Application();
            Outlook.NameSpace   mapiNS = olApp.GetNamespace("MAPI");

            string profile = "";

            mapiNS.Logon(profile, null, null, null);

            Outlook.AppointmentItem apt = olApp.CreateItem(Outlook.OlItemType.olAppointmentItem);
            apt.Start   = DateTime.Now.AddHours(-3);
            apt.End     = apt.Start.AddHours(1);
            apt.Subject = "Please synch in advance.";
            apt.Save();
            apt.Send();
        }
Ejemplo n.º 22
0
        public static void Outlook()
        {
            Microsoft.Office.Interop.Outlook.Application Application = null;
            // Si aucun processus n'est détecté, on crée une nouvelle instance d'Outlook avec les logs d'un profil par défaut

            OutLook._Application outlookObj = new OutLook.Application();

            OutLook.NameSpace MSO_Namespace = Application.GetNamespace("MAPI");
            MSO_Namespace.Logon("*****@*****.**", "134697oki", Missing.Value, Missing.Value);      // Variable de log outlook UserID et Password
            MSO_Namespace = null;
            OutLook.MAPIFolder BoiteReception =
                Application.ActiveExplorer().Session.GetDefaultFolder(OutLook.OlDefaultFolders.olFolderInbox);


            OutLook.Items Mail_Unread = BoiteReception.Items.Restrict("[Unread]=true");
            MessageBox.Show(("Nombre de mail non lus : {0}" + Mail_Unread.Count));
        }
Ejemplo n.º 23
0
        private static Outlook.Application GetApplicationObject()
        {
            Outlook.Application application = null;
            if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
            {
                application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
            }
            else
            {
                application = new Outlook.Application();
                Outlook.NameSpace nameSpace = application.GetNamespace("MAPI");
                nameSpace.Logon("", "", Missing.Value, Missing.Value);
                nameSpace = null;
            }

            return(application);
        }
Ejemplo n.º 24
0
        //Получает все учетные записи с почты.
        private void EnumerateGAL()
        {
            try
            {
                Outlook.Application app = new Outlook.Application();
                Outlook.NameSpace   ns  = app.GetNamespace("MAPI");
                ns.Logon("", "", false, true);

                Outlook.AddressList gal = ns.Session.GetGlobalAddressList();
                progressBar1.Maximum = gal.AddressEntries.Count;
                if (gal != null)
                {
                    int n = 1;
                    for (int i = 1; i <= gal.AddressEntries.Count; i++)
                    {
                        Outlook.AddressEntry addrEntry = gal.AddressEntries[i];
                        if (addrEntry.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry ||
                            addrEntry.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
                        {
                            Outlook.ExchangeUser exchUser = addrEntry.GetExchangeUser();
                            Program.UpdataUsers.Add(exchUser.Name, exchUser.PrimarySmtpAddress);
                            progressBar1.Value = i;
                        }
                        #region один логин выпадает там
                        //if (addrEntry.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeDistributionListAddressEntry)
                        //{
                        //    Outlook.ExchangeDistributionList exchDL = addrEntry.GetExchangeDistributionList();
                        //    //MessageBox.Show(exchDL.Name + " " + exchDL.PrimarySmtpAddress);
                        //        using (StreamWriter sw = new StreamWriter(nameUsers2, true, System.Text.Encoding.Default))
                        //        {
                        //            sw.WriteLine("2 file: " + exchDL.Name + " - " + exchDL.PrimarySmtpAddress);
                        //        }
                        //    progressBar1.Value = i;
                        //}
                        #endregion
                        n++;
                    }
                    if (n > gal.AddressEntries.Count)
                    {
                        progressBar1.Value = 0;
                    }
                    Close();
                }
            }
            catch (Exception e) { MessageBox.Show(e.Message); }
        }
Ejemplo n.º 25
0
        public void StartSession()
        {
            _olApp       = new Outlook.Application();
            _olNamespace = _olApp.Session;

            if (_olNamespace != null)
            {
                _olNamespace.Logon(ShowDialog: true, NewSession: false);

                _olFolder = _olNamespace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderOutbox);

                if (_olFolder != null)
                {
                    _olMailItem = _olFolder.Items.Add(Outlook.OlItemType.olMailItem);
                }
            }
        }
Ejemplo n.º 26
0
        static void VagtplanOutlook(string pSlutDT)
        {
            DateTime    SlutDT      = DateTime.Parse(pSlutDT);
            clsTemplate objTemplate = new clsTemplate();

            Outlook.Application oApp = new Outlook.Application();
            Outlook.NameSpace   oNS  = oApp.GetNamespace("mapi");
            oNS.Logon(Missing.Value, Missing.Value, true, true);
            Outlook.MAPIFolder oCalendar = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);
            Outlook.Items      oItems    = oCalendar.Items;
            string             dayfilter = "[Start] >= '" + DateTime.Today.Date.ToString("g") + "' AND [End] < '" + SlutDT.Date.ToString("g") + "'";
            string             subjectfilter;

            if (oApp.Session.DefaultStore.IsInstantSearchEnabled)
            {
                subjectfilter = "@SQL=\"urn:schemas:httpmail:subject\" ci_startswith '" + objTemplate.Tekst + "'";
            }
            else
            {
                subjectfilter = "@SQL=\"urn:schemas:httpmail:subject\" like '%" + objTemplate.Tekst + "%'";
            }

            Outlook.Items oDagItems = oItems.Restrict(dayfilter).Restrict(subjectfilter);
            for (int i = oDagItems.Count; i > 0; i--)
            {
                oDagItems[i].Delete();
            }

            for (DateTime dt = DateTime.Today; dt.Date <= SlutDT.Date; dt = dt.AddDays(1).Date)
            {
                recTemplate rec = objTemplate.getDag(dt);

                if (!rec.Fri)
                {
                    Outlook.AppointmentItem oAppt = (Outlook.AppointmentItem)oItems.Add(Outlook.OlItemType.olAppointmentItem);
                    oAppt.Subject     = objTemplate.Tekst; // set the subject
                    oAppt.Start       = dt.Date.Add((TimeSpan)rec.Start);
                    oAppt.End         = dt.Date.Add((TimeSpan)rec.S**t);
                    oAppt.ReminderSet = false;                                   // Set the reminder
                    oAppt.Importance  = Outlook.OlImportance.olImportanceNormal; // appointment importance
                    oAppt.BusyStatus  = Outlook.OlBusyStatus.olBusy;
                    oAppt.Save();
                }
            }
        }
Ejemplo n.º 27
0
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            string FilePath = @"E:\Aspose\Aspose VS VSTO\Sample Files\ExportEmail.msg";

            // 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.SaveAs(FilePath, _missing);
        }
Ejemplo n.º 28
0
        static Boolean checkOutlook()
        {
            string OutlookPath = @"C:\Program Files (x86)\Microsoft Office\Office15\Outlook.exe";

            if (File.Exists(@"C:\Program Files (x86)\Microsoft Office\Office15\Outlook.exe"))
            {
                OutlookPath = @"C:\Program Files (x86)\Microsoft Office\Office15\Outlook.exe";
            }

            else if (File.Exists(@"C:\Program Files (x86)\Microsoft Office\Office16\Outlook.exe"))
            {
                OutlookPath = @"C:\Program Files (x86)\Microsoft Office\Office16\Outlook.exe";
            }

            else if (File.Exists(@"C:\Program Files (x86)\Microsoft Office\root\Office16\Outlook.exe"))
            {
                OutlookPath = @"C:\Program Files (x86)\Microsoft Office\root\Office16\Outlook.exe";
            }

            else
            {
                Console.WriteLine("Outlook not installed, exiting.");
                Environment.Exit(0);
            }

            Process[]           pname       = Process.GetProcessesByName("Outlook");
            Outlook.Application application = null;

            if (pname.Length == 0)
            {
                Console.WriteLine("Outlook not running, I will start it for you minimized\n");
                application = new Outlook.Application();
                Outlook.NameSpace nameSpace = application.GetNamespace("MAPI");
                nameSpace.Logon("Outlook", "", Missing.Value, Missing.Value);
                nameSpace = null;
                Thread.Sleep(10000);
                return(true);
            }
            else
            {
                return(false);
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Get all possible apointments for a specific email for X days
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="Days"></param>
        /// <returns></returns>
        private List <OutlookCalendarItem> _GetAppointmentsInRange(string UserName, int Days)
        {
            List <OutlookCalendarItem> ret = new List <OutlookCalendarItem>();

            if (ConnectToServer() == false)
            {
                return(ret);
            }

            Outlook.NameSpace oNS = outlookObj.GetNamespace("mapi");
            oNS.Logon(Missing.Value, Missing.Value, true, true);

            Outlook.Recipient oRecip    = (Outlook.Recipient)oNS.CreateRecipient(UserName);
            Outlook.Folder    calFolder = null;
            try
            {
                calFolder = (Outlook.MAPIFolder)oNS.GetSharedDefaultFolder(oRecip, Outlook.OlDefaultFolders.olFolderCalendar) as Outlook.Folder;
            }
            catch
            {
                return(ret);
            }

            //            Outlook.Folder calFolder = outlookObj.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar) as Outlook.Folder;
            DateTime start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0, 0);
            DateTime end   = start.AddDays(Days);

            Outlook.Items rangeAppts = GetAppointmentsInRange(calFolder, start, end);
            if (rangeAppts != null)
            {
                foreach (Outlook.AppointmentItem item in rangeAppts)
                {
                    OutlookCalendarItem ci = new OutlookCalendarItem();
                    ci.Start        = item.Start;
                    ci.Duration     = item.Duration;
                    ci.ResponseType = (OutlookResponseStatus)item.ResponseStatus;
                    ret.Add(ci);
                }
            }

            return(ret);
        }
Ejemplo n.º 30
0
 private Microsoft.Office.Interop.Outlook.Application GetApplicationObject()
 {
     Microsoft.Office.Interop.Outlook.Application application = null;
     // Check whether there is an Outlook process running.
     if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
     {
         // If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
         application = Marshal.GetActiveObject("Outlook.Application") as Microsoft.Office.Interop.Outlook.Application;
     }
     else
     {
         // If not, create a new instance of Outlook and log on to the default profile.
         application = new Microsoft.Office.Interop.Outlook.Application();
         Microsoft.Office.Interop.Outlook.NameSpace nameSpace = application.GetNamespace("MAPI");
         nameSpace.Logon("", "", Missing.Value, Missing.Value);
         nameSpace = null;
     }
     // Return the Outlook Application object.
     return(application);
 }
Ejemplo n.º 31
0
        /// <summary>
        /// Restituisce un'istanza di Outlook (quella aperta se ce n'è una, una nuova altrimenti).
        /// </summary>
        /// <returns>Istanza di Outlook.</returns>
        protected Outlook.Application GetOutlookInstance()
        {
            Outlook.Application application = null;
            try
            {
                // If so, use the GetActiveObject method to obtain the process and cast it to an Application object.
                application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
            }
            catch
            {
                // If not, create a new instance of Outlook and log on to the default profile.
                application = new Outlook.Application();
                Outlook.NameSpace nameSpace = application.GetNamespace("MAPI");
                nameSpace.Logon("", "");
                nameSpace = null;
            }

            // Return the Outlook Application object.
            return(application);
        }
Ejemplo n.º 32
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);
            }
        }
Ejemplo n.º 33
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);
            }
        }
Ejemplo n.º 34
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());
            }
        }
Ejemplo n.º 35
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;
        }
Ejemplo n.º 36
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;
        }