Search code examples
.netexchange-serveroutlook-addin

Getting calendar appointments from multiple accounts


I'm currently creating an Outlook Add-In and I'm using the function below to get all the calendar appointments from all the accounts I'm connected to in Outlook.

private List<Outlook.MAPIFolder> _calendarsFolder = new List<Outlook.MAPIFolder>();
private List<Outlook.Items> _calendarsItems = new List<Outlook.Items>();

private void GetCalendarsItems(object sender, EventArgs e)
{
    Outlook.NameSpace session = Globals.ThisAddIn.Application.Session;
    Outlook.Accounts accounts = session.Accounts;

    foreach (Outlook.Account account in accounts)
    {
        Outlook.Recipient recipient = session.CreateRecipient(account.DisplayName);
        Outlook.MAPIFolder calendar = null;

        try
        {
            calendar = session.GetSharedDefaultFolder(recipient, Outlook.OlDefaultFolders.olFolderCalendar);
        }
        catch (Exception)
        {
            continue;
        }

        if (calendar != null)
        {
            var calendarItems = calendar.Items;
            AttachEvents(calendarItems);

            _calendarsFolder.Add(calendar);
            _calendarsItems.Add(calendarItems);

            foreach (Outlook.AppointmentItem item in calendarItems)
            {
                if (Select_T_OutlookEvent_Exists(item.GlobalAppointmentID)) continue;

                var outlookEvent = new T_OutlookEvent()
                {
                    Id = item.GlobalAppointmentID,
                    Title = item.Subject,
                    Description = item.Body,
                    Location = item.Location,
                    Organizer = item.GetOrganizer().Name
                };

                Insert_T_OutlookEvent(outlookEvent);
            }
        }
    }
}

The problem is that I only get the appointments from one account (connected to Exchange, it is also the primary account). An exception is thrown on the GetSharedDefaultFolder function call (COMException: The operation failed because of a registry or installation problem. Restart Outlook and try again. If the problem persists, reinstall) for all the other accounts: one account that is connected to Exchange, the other two are not.

Thanks in advance for your help!


Solution

  • GetSharedDefaultFolder is for delegation scenarios and won't give you access to all of your local/personal Calendars. Instead, loop through NameSpace.Stores and use Store.GetDefaultFolder to get the Calendar for each configured account/store.