public MailStoreProviderOM(string mailboxName, bool disableOutlookPrompt) { _disableOutlookPrompt = disableOutlookPrompt; if (_disableOutlookPrompt) { ConfigOutlookPrompts(false); } ConnectToOutlook(); if (mailboxName != null) { mailboxName = mailboxName.ToLower(); _store = AllMailStores().FirstOrDefault(x => x.DisplayName.ToLower() == mailboxName); if (_store == null) { throw new ArgumentException(string.Format("Cannot find store (mailbox) {0} in default profile", mailboxName)); } } else { _store = _outlook.Session.DefaultStore; } _userAccount = FindUserAccount(); _rootFolder = new Lazy<IMailFolder>(GetRootFolder); }
public OutlookDirectoryInfo(string seed) { Outlook.Store store = oOutlook.Session.GetStoreFromID(seed); folder = (Outlook.Folder)store.GetRootFolder(); Name = folder.Name; FullName = folder.FullFolderPath; }
public MailStoreProviderOM(string mailboxName, bool disableOutlookPrompt) { _disableOutlookPrompt = disableOutlookPrompt; if (_disableOutlookPrompt) { ConfigOutlookPrompts(false); } ConnectToOutlook(); if (mailboxName != null) { mailboxName = mailboxName.ToLower(); _store = AllMailStores().FirstOrDefault(x => x.DisplayName.ToLower() == mailboxName); if (_store == null) { throw new ArgumentException(string.Format("Cannot find store (mailbox) {0} in default profile", mailboxName)); } } else { _store = _outlook.Session.DefaultStore; } _userAccount = FindUserAccount(); _rootFolder = new Lazy <IMailFolder>(GetRootFolder); }
private static bool IsMailItemHasFlaggedPreviousMail(Outlook.MailItem mailItem) { bool answer = false; if (mailItem is Outlook.MailItem) { Outlook.Folder folder = mailItem.Parent as Outlook.Folder; Debug.Assert(folder != null); Outlook.Store store = folder.Store; if ((store != null) && (store.IsConversationEnabled == true)) { Outlook.Conversation conv = mailItem.GetConversation(); if (conv != null) { Outlook.SimpleItems simpleItems = conv.GetRootItems(); foreach (object item in simpleItems) { if (item is Outlook.MailItem) { bool result = IsMailItemOrAnyItsChildrenFlagged(item as Outlook.MailItem, conv); if (result == true) { answer = true; } } } } } } return(answer); }
public MailTable IndexSinglePst() { Microsoft.Office.Interop.Outlook.Application otlApplication = new Microsoft.Office.Interop.Outlook.Application(); try { Outlook.NameSpace otlNameSpace = otlApplication.GetNamespace("MAPI"); Outlook.Store otlStore = otlNameSpace.PickFolder().Store; System.IO.FileInfo fi = new System.IO.FileInfo(otlStore.FilePath); this.mailTable = new MailTable((new System.IO.FileInfo(otlStore.FilePath)).Name); this.mailTable.ModifiedData = fi.FullName + fi.Length.ToString(); //this.mailTable.BaseTable = GMS.MailTable.getTable(this.mailTable.BaseTable, basetable.Select("StoreID<>'"+otlStore.StoreID.ToString()+"'")); try { analyseFolder((Outlook.Folder)otlStore.GetRootFolder()); } catch { } } catch { } finally { otlApplication = null; } return(this.mailTable); }
/// <summary> /// Constructor. Initiated from MailConnection object /// </summary> /// <param name="store">Outlook.Store oibject</param> public MailStore(Outlook.Store store) { _store = store; _outlook = store.Application; // Initalizes the dictionary of supported default Outlook folders _folderTypes.Add("olFolderInbox", Outlook.OlDefaultFolders.olFolderInbox); _folderTypes.Add("olFolderDeletedItems", Outlook.OlDefaultFolders.olFolderDeletedItems); _folderTypes.Add("olFolderDrafts", Outlook.OlDefaultFolders.olFolderDrafts); _folderTypes.Add("olFolderJunk", Outlook.OlDefaultFolders.olFolderJunk); _folderTypes.Add("olFolderOutbox", Outlook.OlDefaultFolders.olFolderOutbox); _folderTypes.Add("olFolderSentMail", Outlook.OlDefaultFolders.olFolderSentMail); // Finding Account associated with this store // Loops over the Accounts collection of the current Outlook session. _userAccount = null; Outlook.Accounts accounts = _outlook.Session.Accounts; foreach (Outlook.Account account in accounts) { // When the e-mail address matches, return the account. if (account.SmtpAddress == _store.DisplayName) { _userAccount = account; } } if (null == _userAccount) { throw new System.Exception(string.Format("No Account with SmtpAddress: {0} exists!", _store.DisplayName)); } }
/// <summary> /// Performs the actions required to handle a new store. /// </summary> /// <param name="rawStore">The new store. Ownership is transferred</param> private void StoreAdded(NSOutlook.Store rawStore) { IStore store = new StoreWrapper(rawStore); try { Logger.Instance.Trace(this, "New store: {0}", rawStore.DisplayName); AccountWrapper account = TryCreateFromRegistry(store); if (account == null) { // Add it to the cache so it is not evaluated again. _accountsByStoreId.Add(store.StoreID, null); Logger.Instance.Trace(this, "Not an account store: {0}", store.DisplayName); } else { Logger.Instance.Trace(this, "New account store: {0}: {1}", store.DisplayName, account); // Account has taken ownership of the store store = null; OnAccountDiscovered(account); } } catch (System.Exception e) { Logger.Instance.Error(this, "Event_StoreAdded Exception: {0}", e); } finally { store?.Dispose(); } }
public void FindLastInConversation(Outlook.MailItem mailItem) { if (mailItem is Outlook.MailItem) { // Determine the store of the mail item. Outlook.Folder folder = mailItem.Parent as Outlook.Folder; Outlook.Store store = folder.Store; if (store.IsConversationEnabled) { // Obtain a Conversation object. Outlook.Conversation conv = mailItem.GetConversation(); // Check for null Conversation. if (conv != null) { // Obtain Table that contains rows Outlook.Table table = conv.GetTable(); int count = table.GetRowCount(); Logger.Log("Conversation Items Count: " + count.ToString()); table.MoveToStart(); if (!table.EndOfTable) { // lastRow conatins the last item from the conversation Outlook.Row lastRow = table.GetNextRow(); //Logger.Log(lastRow["Subject"] + " Modified: " + lastRow["LastModificationTime"]); } } } } }
public void ReportHam(object sender, RibbonControlEventArgs e) { Outlook.Application outlookApp = this.Application; DialogResult result = MessageBox.Show(global::OutlookSPAMReport.AllResources.MessageBoxConfirmReportHam, "Spam Reporter", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.No) { return; } IEnumerable <Outlook.MailItem> selectedEmails = GetSelectedEmails(); try { Outlook.MailItem hamReportMailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem); string storeID = outlookApp.ActiveExplorer().CurrentFolder.StoreID; foreach (Outlook.Account account in outlookApp.Session.Accounts) { if (account.DeliveryStore.StoreID == storeID) { hamReportMailItem.SendUsingAccount = account; break; } } hamReportMailItem.Body = "Report ham"; hamReportMailItem.Subject = "Report ham"; hamReportMailItem.To = appSettings.Default.HamTo; foreach (Outlook.MailItem oneEmail in selectedEmails) { hamReportMailItem.Attachments.Add(oneEmail, Outlook.OlAttachmentType.olEmbeddeditem); } hamReportMailItem.Send(); } catch (Exception ex) { MessageBox.Show(ex.Message); } foreach (Outlook.MailItem oneEmail in selectedEmails) { try { Outlook.Folder parentFolder = (Outlook.Folder)oneEmail.Parent; Outlook.Store itemStore = parentFolder.Store; Outlook.MAPIFolder inboxFolder = itemStore.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox); if (parentFolder.FolderPath != inboxFolder.FolderPath) { oneEmail.Move(inboxFolder); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
// TODO: extension methods for this public static IStore Wrap(NSOutlook.Store obj, bool mustRelease = true) { if (obj == null) { return(null); } StoreWrapper wrapped = new StoreWrapper(obj); wrapped.MustRelease = mustRelease; return(wrapped); }
private static Outlook.Store AddStore(Outlook.Application app, string pstPath, string displayName) { app.Session.AddStoreEx(pstPath, Outlook.OlStoreType.olStoreDefault); Outlook.Folder lastFolder = app.GetNamespace("MAPI").Folders.GetLast() as Outlook.Folder; lastFolder.Name = displayName; Outlook.Store store = GetStore(app, pstPath); return(store); // [TODO] set 'Display reminders and tasks from this folder in the To-Do Bar' checkbox }
public Reporter() { Console.ForegroundColor = ConsoleColor.Black; Console.BackgroundColor = ConsoleColor.White; Console.WriteLine("Starting PK Reporter\nWritten by Juan Menendez\n\n"); Console.ResetColor(); OutlookApp = GetApplicationObject(); PKStore = OutlookApp.Session.GetStoreFromID(GetStoreID(OutlookApp.Session.Stores)); PKAlerts = (Outlook.Folder)PKStore.GetRootFolder(); }
private static void Verificar_Correos(string directory_name, DateTime fec) { bool verfal; verfal = Existe_Buzon(); if ((verfal == true)) { ns = ok.Session; stores = ns.Stores; // cnt debe empezar desde 1 (indice 0 no existe). int cnt = 1; foreach (Outlook.Store store in ns.Stores) { // Si se quiere buscar otro buzon, se debe cambiar el valor en App.Config if (store.DisplayName.ToLower().Contains(ConfigurationManager.AppSettings.Get("busqueda_buzon").ToLower().ToString())) { //MessageBox.Show(store.DisplayName.ToString()); break; } else { // Hasta que no entre en el if cnt se incremente (cnt representa las carpetas del buzon por indices). cnt++; // MsgBox(store.DisplayName.ToString) } } // stores(cnt) es el buz�n el cual se buscar�n los correos a descargar. store = stores[cnt]; mailboxFolder = store.GetRootFolder(); folders = mailboxFolder.Folders; for (int j = 1; (j <= folders.Count); j++) { folder = folders[j]; // folderList += folder.Name + Environment.NewLine if ((folder.Name.ToLower().Equals(directory_name.ToLower()))) { // MsgBox(folder.Name, , "Carpeta de Busqueda") SeleccionarCarpeta(folder, fec); j = folders.Count; } } // MessageBox.Show(folderList, "Lista Outlook") //folderList = null; Marshal.ReleaseComObject(folder); } }
private bool EmailShouldBeArchived(EmailArchiveType type, Outlook.Store store) { var storeId = store.StoreID; switch (type) { case EmailArchiveType.Inbound: return(settings.AccountsToArchiveInbound.Contains(storeId)); case EmailArchiveType.Sent: return(settings.AccountsToArchiveOutbound.Contains(storeId)); default: return(false); } }
/// <summary> /// Get the categories as configured in Outlook and store in class /// </summary> /// <param name="oApp"></param> /// <param name="store"></param> public void Get(Outlook.Application oApp, Outlook.Store store) { if (Settings.Instance.OutlookService == OutlookOgcs.Calendar.Service.DefaultMailbox) { this.categories = oApp.Session.Categories; } else { try { this.categories = store.GetType().GetProperty("Categories").GetValue(store, null) as Outlook.Categories; } catch (System.Exception ex) { OGCSexception.Analyse(ex, true); this.categories = oApp.Session.Categories; } } }
public void List_Of_Folders() { Outlook.NameSpace ns = null; Outlook.Stores stores = null; Outlook.Store store = null; Outlook.MAPIFolder rootFolder = null; Outlook.Folders folders = null; Outlook.MAPIFolder folder = null; string folderList = string.Empty; try { Outlook.Application oApp = new Outlook.Application(); ns = oApp.Session; stores = ns.Stores; store = stores[1]; rootFolder = store.GetRootFolder(); folders = rootFolder.Folders; for (int i = 1; i < folders.Count; i++) { folder = folders[i]; folderList += folder.Name + Environment.NewLine; //if (folder != null) // // Marshal.ReleaseComObject(folder); } MessageBox.Show(folderList); } //finally //{ // if (folders != null) // Marshal.ReleaseComObject(folders); // if (folders != null) // Marshal.ReleaseComObject(folders); // if (rootFolder != null) // Marshal.ReleaseComObject(rootFolder); // if (store != null) // Marshal.ReleaseComObject(store); // if (stores != null) // Marshal.ReleaseComObject(stores); // if (ns != null) // Marshal.ReleaseComObject(ns); //} catch (Exception ex) { } }
public bool TrySetStore(string storeDescriptor) { if (string.IsNullOrWhiteSpace(storeDescriptor)) { m_store = m_session.GetStores().FirstOrDefault(); } else { if (m_session.TryGetStore(storeDescriptor, out m_store) == false) { m_session.AddStore(storeDescriptor); m_removeStore = m_session.TryGetStore(storeDescriptor, out m_store); } } return(m_store != null); }
/// <summary> /// Sets the default inbox to be used when preforming an flookup /// </summary> /// <param name="inbox"> default inbox name </param> /// <param name="stores"> a list of each store for a particular outlook account</param> public void setDefaultEmail(string inbox, List <Outlook.Store> stores) { try { Outlook.Store store = this.findInbox(inbox, stores); Configuration config = ConfigurationManager.OpenExeConfiguration(""); //ConfigurationManager.AppSettings.Settings["defaultStore"].Value = inbox; config.AppSettings.Settings.Remove("defaultStore"); config.AppSettings.Settings.Add("defaultStore", inbox); config.Save(ConfigurationSaveMode.Modified); } catch (InvalidInboxException e) { Console.WriteLine(e.Message); Console.WriteLine(this.getAccounts(stores)); } }
private void LoadContactsList() { Outlook.Application outlookApp = new Microsoft.Office.Interop.Outlook.Application(); Outlook.Folder contactsFolder = outlookApp.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olPublicFoldersAllPublicFolders) as Outlook.Folder; Outlook.Folder currentFolder = outlookApp.ActiveExplorer().CurrentFolder as Outlook.Folder; Outlook.Store currentStore = currentFolder.Store; Outlook.AddressList addressList = this.GetGlobalAddressList(outlookApp, currentStore); Outlook.AddressEntries entries = addressList.AddressEntries; this._contactsList = new List <Contact>(); foreach (Outlook.AddressEntry entry in entries) { Outlook.ExchangeDistributionList distList = entry.GetExchangeDistributionList(); Outlook.ExchangeUser user = entry.GetExchangeUser(); Outlook.ContactItem contact = entry.GetContact(); if (distList != null) { this._contactsList.Add(new Contact(distList.Name, distList.PrimarySmtpAddress)); } if (contact != null) { this._contactsList.Add(new Contact(contact.FirstName + " " + contact.LastName, contact.IMAddress)); } if (user != null) { if (user.FirstName == null && user.LastName == null) { this._contactsList.Add(new Contact(user.Name, user.PrimarySmtpAddress)); } else { this._contactsList.Add(new Contact(user.FirstName + " " + user.LastName, user.PrimarySmtpAddress)); } } } }
public Outlook.Account GetDefaultAccount(Outlook.Application application) { // Get the Store for CurrentFolder. Outlook.Folder folder = application.ActiveExplorer().CurrentFolder as Outlook.Folder; Outlook.Store store = folder.Store; Outlook.Accounts accounts = application.Session.Accounts; // Enumerate accounts to find // account.DeliveryStore for store. foreach (Outlook.Account account in accounts) { if (account.DeliveryStore.StoreID == store.StoreID) { return(account); } } // If you get here, no matching account was found. throw new System.Exception(string.Format("No Account found!")); }
private static Outlook.Folder GetBackupFolder(Outlook.MailItem mailItem) { string mailReceivedYear = mailItem.ReceivedTime.Year.ToString(); string mailReceivedMonth = mailItem.ReceivedTime.Month.ToString(); string backupName = @"" + mailReceivedYear + @"_" + mailReceivedMonth; string backupStoreFileName = Config.EmailBackupPath + @"\" + backupName + @".pst"; Outlook.Store store = GetStore(mailItem.Application, backupStoreFileName); if (store == null) { AddStore(mailItem.Application, backupStoreFileName, backupName); } string backupFolderName = @"\\" + backupName; Outlook.Folder backupFolder = GetFolder(mailItem.Application, backupFolderName); return(backupFolder); }
/// <summary> /// Get the categories as configured in Outlook and store in class /// </summary> /// <param name="oApp"></param> /// <param name="calendar"></param> public void Get(Outlook.Application oApp, Outlook.MAPIFolder calendar) { Outlook.Store store = null; try { if (Settings.Instance.OutlookService == OutlookOgcs.Calendar.Service.DefaultMailbox) { this.categories = oApp.Session.Categories; } else { try { store = calendar.Store; this.categories = store.GetType().GetProperty("Categories").GetValue(store, null) as Outlook.Categories; } catch (System.Exception ex) { log.Warn("Failed getting non-default mailbox categories. " + ex.Message); log.Debug("Reverting to default mailbox categories."); this.categories = oApp.Session.Categories; } } } finally { store = (Outlook.Store)Calendar.ReleaseObject(store); } }
/// <summary> /// Event handler for Stores.StoreAdded event. /// </summary> private void Event_StoreAdded(NSOutlook.Store _) { try { // Accessing the store object causes random crashes, simply iterate to find new stores Logger.Instance.Trace(this, "StoreAdded"); foreach (NSOutlook.Store rawStore in IteratorStoresSafe()) { if (!_accountsByStoreId.ContainsKey(rawStore.StoreID)) { StoreAdded(rawStore); } else { ComRelease.Release(rawStore); } } } catch (System.Exception e) { Logger.Instance.Error(this, "Event_StoreAdded Exception: {0}", e); } }
private static Outlook.MAPIFolder GetCommonViewsFolder() { try { if (null == m_NameSpace) { Initialise(); } Outlook.Store olStore = m_NameSpace.DefaultStore; Outlook.PropertyAccessor olPropertyAccessor = olStore.PropertyAccessor; string commonViewsEntryId = olPropertyAccessor.BinaryToString(olPropertyAccessor.GetProperty(PR_COMMON_VIEWS_ENTRY_ID)); if (commonViewsEntryId != string.Empty) { return(m_NameSpace.GetFolderFromID(commonViewsEntryId)); } return(null); } catch (Exception exception) { Console.WriteLine("Unable to get common views folder. Error: " + exception.ToString()); return(null); } }
/// <summary> /// Finds any folder paths containing a particular folderName /// </summary> /// <param name="folderName"> the folder we are searching for</param> /// <param name="inbox"> the inbox we are looking at</param> public void findFolder(string folderName, Outlook.Store inbox) { string paths = ""; // Get the root folder Outlook.Folder root = inbox.GetRootFolder() as Outlook.Folder; // get results paths = this.EnumerateFolders(root); //Console.WriteLine(paths); // create a regex for the folderName MatchCollection mc = Regex.Matches(paths, ".*" + folderName + ".*"); if (mc.Count.Equals(0)) { throw new InvalidFolderException("Folder " + folderName + " could not be found."); } foreach (Match match in mc) { Console.WriteLine("\t" + match.ToString().Substring(2)); } }
private bool EmailShouldBeArchived(EmailArchiveReason type, Outlook.Store store) { bool result; var storeId = store.StoreID; switch (type) { case EmailArchiveReason.Inbound: result = Properties.Settings.Default.AccountsToArchiveInbound != null && Properties.Settings.Default.AccountsToArchiveInbound.Contains(storeId); break; case EmailArchiveReason.Outbound: result = Properties.Settings.Default.AccountsToArchiveOutbound != null && Properties.Settings.Default.AccountsToArchiveOutbound.Contains(storeId); break; default: result = false; break; } return(result); }
private void GetAttachmentsFromConversation(MailItem mailItem) { if (mailItem == null) { return; } if (mailItem.Attachments.CountNonEmbeddedAttachments() > 0) { return; } System.Collections.Generic.Stack <MailItem> st = new System.Collections.Generic.Stack <MailItem>(); // Determine the store of the mail item. Outlook.Folder folder = mailItem.Parent as Outlook.Folder; Outlook.Store store = folder.Store; if (store.IsConversationEnabled == true) { // Obtain a Conversation object. Outlook.Conversation conv = mailItem.GetConversation(); // Check for null Conversation. if (conv != null) { // Obtain Table that contains rows // for each item in the conversation. Outlook.Table table = conv.GetTable(); _logger.Debug("Conversation Items Count: " + table.GetRowCount().ToString()); _logger.Debug("Conversation Items from Root:"); // Obtain root items and enumerate the conversation. Outlook.SimpleItems simpleItems = conv.GetRootItems(); foreach (object item in simpleItems) { // In this example, enumerate only MailItem type. // Other types such as PostItem or MeetingItem // can appear in the conversation. if (item is Outlook.MailItem) { Outlook.MailItem mail = item as Outlook.MailItem; Outlook.Folder inFolder = mail.Parent as Outlook.Folder; string msg = mail.Subject + " in folder [" + inFolder.Name + "] EntryId [" + (mail.EntryID.ToString() ?? "NONE") + "]"; _logger.Debug(msg); _logger.Debug(mail.Sender); _logger.Debug(mail.ReceivedByEntryID); if (mail.EntryID != null && (mail.Sender != null || mail.ReceivedByEntryID != null)) { st.Push(mail); } } // Call EnumerateConversation // to access child nodes of root items. EnumerateConversation(st, item, conv); } } } while (st.Count > 0) { MailItem it = st.Pop(); if (it.Attachments.CountNonEmbeddedAttachments() > 0) { //_logger.Debug(it.Attachments.CountNonEmbeddedAttachments()); try { if (mailItem.IsMailItemSignedOrEncrypted()) { if (MessageBox.Show(null, "Es handelt sich um eine signierte Nachricht. Soll diese für die Anhänge ohne Zertifikat dupliziert werden?", "Nachricht duplizieren?", MessageBoxButtons.YesNo) == DialogResult.Yes) { mailItem.Close(OlInspectorClose.olDiscard); mailItem = mailItem.Copy(); mailItem.Unsign(); mailItem.Save(); mailItem.Close(OlInspectorClose.olDiscard); mailItem.Save(); } else { st.Clear(); break; } } mailItem.CopyAttachmentsFrom(it); mailItem.Save(); } catch (System.Exception ex) { //mailItem.Close(OlInspectorClose.olDiscard); MessageBox.Show(ex.Message); } st.Clear(); } } st.Clear(); Marshal.ReleaseComObject(mailItem); }
public static void Main(string[] args) { FolderFinder finder = new FolderFinder(); // case where user supplys a folder name however no -s option // and specifies only a folder name if (args.Length.Equals(1)) { // User option which retreives all the stores(inboxes) for a particular account if (args[0].Equals("-s")) { var stores = finder.getStores(); Console.Write(finder.getAccounts(stores)); } // User option which retreives the default mailbox else if (args[0].Equals("-d")) { try { Console.WriteLine(finder.getDefaultEmail()); } catch (InvalidInboxException e) { Console.WriteLine(e.Message); } } else { try { // Retrieve all the stores in an account var stores = finder.getStores(); // Search for the specified Store // This is the default store Outlook.Store inbox = finder.findInbox(finder.getDefaultEmail(), stores); finder.findFolder(args[0], inbox); } catch (InvalidInboxException e) { Console.WriteLine(e.Message); } catch (InvalidFolderException e) { Console.WriteLine(e.Message); } } } else if (args.Length == 2) { if (!args[0].Equals("-d")) { finder.help(); } else { List <Outlook.Store> stores = finder.getStores(); finder.setDefaultEmail(args[1], stores); } } // User uses option -s and specifies an inbox followed by a folder name else if (args.Length == 3) { // i stands for inbox if (!args[0].Equals("-i")) { Console.WriteLine("You've entered an invalid option"); finder.help(); } else { try { // Retrieve all the stores in an account var stores = finder.getStores(); // Search for the specified Store // This is the default store Outlook.Store inbox = finder.findInbox(args[1], stores); finder.findFolder(args[2], inbox); } catch (InvalidInboxException e) { Console.WriteLine(e.Message); } catch (InvalidFolderException e) { Console.WriteLine(e.Message); } } } // Error message else { finder.help(); } }
private void ConnectAndLoad() { //TODO use a new/temporary profile and other security measures this._application = new Outlook.Application(); this._application.Session.AddStore(this.Path); Outlook.Stores stores = this._application.Session.Stores; foreach (Outlook.Store store in stores) { if (store.FilePath == this.Path) { this._store = store; } } this._connected = true; }
internal static bool TryGetStore(this Outlook.NameSpace item, string descriptor, out Outlook.Store result) { bool success = false; result = default; foreach (var store in item.GetStores()) { if (string.Equals(descriptor, store.DisplayName, StringComparison.CurrentCultureIgnoreCase) || string.Equals(descriptor, store.FilePath, StringComparison.InvariantCultureIgnoreCase)) { result = store; success = true; } } return(success); }
public void Dispose(bool disposing) { if (this._disposed) { return; } if (disposing) { if (this._application != null) { this.UnloadAndDisconnect(); } } //release resources this._application = null; this._store = null; this._disposed = true; }
internal static Outlook.Account GetAccount(this Outlook.Folder _folder) { Outlook.Store store = null; Outlook.NameSpace session = null; Outlook.Accounts accounts = null; try { store = _folder.Store; session = _folder.Session; accounts = session.Accounts; foreach (Outlook.Account account in accounts) { Outlook.Store accountStore = null; try { accountStore = account.DeliveryStore; if (accountStore.StoreID == store.StoreID) { return(account); } else { Marshal.ReleaseComObject(account); } } finally { if (accountStore != null) { Marshal.ReleaseComObject(accountStore); accountStore = null; } } } } finally { if (store != null) { Marshal.ReleaseComObject(store); store = null; } if (session != null) { Marshal.ReleaseComObject(session); session = null; } if (accounts != null) { Marshal.ReleaseComObject(accounts); accounts = null; } } return(null); }
// OnMyButtonClick routine handles all button click events // and displays IRibbonControl.Context in message box public void OnMyButtonClick(Office.IRibbonControl control) { string msg = string.Empty; if (control.Context is Outlook.AttachmentSelection) { msg = "Context=AttachmentSelection" + "\n"; Outlook.AttachmentSelection attachSel = control.Context as Outlook.AttachmentSelection; foreach (Outlook.Attachment attach in attachSel) { msg = msg + attach.DisplayName + "\n"; } } else if (control.Context is Outlook.Folder) { msg = "Context=Folder" + "\n"; Outlook.Folder folder = control.Context as Outlook.Folder; msg = msg + folder.Name; } else if (control.Context is Outlook.Selection) { msg = "Context=Selection" + "\n"; Outlook.Selection selection = control.Context as Outlook.Selection; if (selection.Count == 1) { OutlookItem olItem = new OutlookItem(selection[1]); msg = msg + olItem.Subject + "\n" + olItem.LastModificationTime; } else { msg = msg + "Multiple Selection Count=" + selection.Count; } } else if (control.Context is Outlook.OutlookBarShortcut) { msg = "Context=OutlookBarShortcut" + "\n"; Outlook.OutlookBarShortcut shortcut = control.Context as Outlook.OutlookBarShortcut; msg = msg + shortcut.Name; } else if (control.Context is Outlook.Store) { msg = "Context=Store" + "\n"; Outlook.Store store = control.Context as Outlook.Store; msg = msg + store.DisplayName; } else if (control.Context is Outlook.View) { msg = "Context=View" + "\n"; Outlook.View view = control.Context as Outlook.View; msg = msg + view.Name; } else if (control.Context is Outlook.Inspector) { msg = "Context=Inspector" + "\n"; Outlook.Inspector insp = control.Context as Outlook.Inspector; if (insp.AttachmentSelection.Count >= 1) { Outlook.AttachmentSelection attachSel = insp.AttachmentSelection; foreach (Outlook.Attachment attach in attachSel) { msg = msg + attach.DisplayName + "\n"; } } else { OutlookItem olItem = new OutlookItem(insp.CurrentItem); msg = msg + olItem.Subject; } } else if (control.Context is Outlook.Explorer) { msg = "Context=Explorer" + "\n"; Outlook.Explorer explorer = control.Context as Outlook.Explorer; if (explorer.AttachmentSelection.Count >= 1) { Outlook.AttachmentSelection attachSel = explorer.AttachmentSelection; foreach (Outlook.Attachment attach in attachSel) { msg = msg + attach.DisplayName + "\n"; } } else { Outlook.Selection selection = explorer.Selection; if (selection.Count == 1) { OutlookItem olItem = new OutlookItem(selection[1]); msg = msg + olItem.Subject + "\n" + olItem.LastModificationTime; } else { msg = msg + "Multiple Selection Count=" + selection.Count; } } } else if (control.Context is Outlook.NavigationGroup) { msg = "Context=NavigationGroup" + "\n"; Outlook.NavigationGroup navGroup = control.Context as Outlook.NavigationGroup; msg = msg + navGroup.Name; } else if (control.Context is Microsoft.Office.Core.IMsoContactCard) { msg = "Context=IMsoContactCard" + "\n"; Office.IMsoContactCard card = control.Context as Office.IMsoContactCard; if (card.AddressType == Office.MsoContactCardAddressType. msoContactCardAddressTypeOutlook) { // IMSOContactCard.Address is AddressEntry.ID Outlook.AddressEntry addr = Globals.ThisAddIn.Application.Session.GetAddressEntryFromID( card.Address); if (addr != null) { msg = msg + addr.Name; } } } else if (control.Context is Outlook.NavigationModule) { msg = "Context=NavigationModule"; } else if (control.Context == null) { msg = "Context=Null"; } else { msg = "Context=Unknown"; } MessageBox.Show(msg, "RibbonXOutlook14AddinCS", MessageBoxButtons.OK, MessageBoxIcon.Information); }
private Outlook.AddressList GetGlobalAddressList(Outlook.Application outlookApp, Outlook.Store store) { // Property string for the UID of a store or address list. string PR_EMSMDB_SECTION_UID = @"http://schemas.microsoft.com/mapi/proptag/0x3D150102"; if (store == null) { throw new ArgumentNullException(); } // Obtain the store UID using the proprety string and // property accessor on the store. Outlook.PropertyAccessor oPAStore = store.PropertyAccessor; // Convert the store UID to a string value. string storeUID = oPAStore.BinaryToString(oPAStore.GetProperty(PR_EMSMDB_SECTION_UID)); // Enumerate each address list associated // with the session. foreach (Outlook.AddressList addrList in outlookApp.Session.AddressLists) { // Obtain the address list UID and convert it to // a string value. Outlook.PropertyAccessor oPAAddrList = addrList.PropertyAccessor; string addrListUID = oPAAddrList.BinaryToString(oPAAddrList.GetProperty(PR_EMSMDB_SECTION_UID)); // Return the address list associated with the store // if the address list UID matches the store UID and // type is olExchangeGlobalAddressList. if (addrListUID == storeUID && addrList.AddressListType == Outlook.OlAddressListType.olExchangeGlobalAddressList) { return(addrList); } } return(null); }