Resumo

Este artigo descreve como utilizar a Biblioteca de Objetos do Microsoft Outlook 10.0 para obter mensagens específicas através do método Encontrar e do método Restringir no Microsoft Visual C#.

Mais Informações

Para utilizar a Biblioteca de Objetos Outlook Microsoft Outlook 10.0 para obter mensagens específicas, siga estes passos:

  1. Inicie o Microsoft Visual Studio .NET ou o Microsoft Visual Studio 2005.

  2. No menu Ficheiro, aponte para Novo e, em seguida, clique em Project.

  3. Na lista de tipos de Projetos Visual C# , clique em Aplicação de Consola. Por predefinição, é criado o ficheiro Class1.cs.Nota No Microsoft Visual C# 2005, clique em Visual C#" na lista tipos de Projetos Visual C# . Por predefinição, é criado Program.cs.

  4. Adicione uma referência à Biblioteca de Objetos do Microsoft Outlook 10.0. Para o fazer, siga estes passos:

    1. No menu Project, clique em Adicionar Referência.

    2. Clique no separador COM, localize Microsoft Outlook 10.0 Biblioteca de Objetos e, em seguida, clique em Selecionar.Nota no Microsoft Visual C# 2005. não tem de clicar em Selecionar.

    3. Na caixa de diálogo Adicionar Referências , clique em OK.

    4. Se lhe for pedido para gerar embrulhos para as bibliotecas que selecionou, clique em Sim.

  5. Na janela do código, substitua o código pelo seguinte:

    using System;using System.Reflection;     // to use Missing.Valuenamespace FilterAppointments{   /// <summary>   /// Summary description for Class1.   /// </summary>   class Class1   {      /// <summary>      /// The main entry point for the application.      /// </summary>      [STAThread]      public static int Main(string[] args)      {         try         {            // Create an Outlook application.            Outlook.Application oApp = new Outlook.Application();            // Get the Mapi NameSpace and the Logon.            Outlook.NameSpace oNS = (Outlook.NameSpace)oApp.GetNamespace("mapi");            // Log on using dialog to choose a profile.            oNS.Logon(Missing.Value, Missing.Value, true, true);             // Alternate Logon using specific profile            // TODO: Change the profile name where it is appropriate.            //oNS.Logon("YourValidProfile", Missing.Value, false, true);             // Get the Calendar folder.            Outlook.MAPIFolder oCalendar = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);            // Get the Items collection in the folder.            Outlook.Items  oItems = (Outlook.Items)oCalendar.Items;            Console.WriteLine("Total Items (unrestricted): " + oItems.Count);            //Include all occurrences of recurring items, and then sort them.            oItems.Sort ("[Start]", false);            oItems.IncludeRecurrences = true;            // Define the string for the search criteria.            String sCriteria;            // Set the criteria for the Date fields.            sCriteria = "[Start] <= '09/01/2002 08:00 AM' and [End] >= '2/15/2002 08:00 PM'";            // Set the criteria for a string field.            // sCriteria = "[Subject] = 'Weekly recurring meeting'";            // Set the criteria for a numeric field.            // Look for meetings that have not been responded to.            // sCriteria = "[ResponseStatus] = " + (Int32)Outlook.OlResponseStatus.olResponseNotResponded)            // Use the Restrict method to reduce the number of items to process.            Outlook.Items oRestrictedItems = oItems.Restrict(sCriteria);            oRestrictedItems.Sort ("[Start]", false);            oRestrictedItems.IncludeRecurrences = true;            Console.WriteLine("Total Items Unrestricted : " + oRestrictedItems.Count);            Outlook.AppointmentItem oAppointment;            //Get each item until item is null.            Outlook.AppointmentItem oAppt;            oAppt = (Outlook.AppointmentItem)oRestrictedItems.GetFirst();            while (oAppt != null)            {               // Console.WriteLine(i.ToString());                Console.WriteLine("  Subject: " + oAppt.Subject.ToString());                Console.WriteLine("  Start time: " + oAppt.Start.ToString());                Console.WriteLine("  End time: " + oAppt.End.ToString());                Console.WriteLine("  Occurrences: " + oAppt.RecurrenceState.ToString());                Console.WriteLine("\n\n");                oAppt = (Outlook.AppointmentItem)oRestrictedItems.GetNext();            }            // Use the Find method to get single match.            sCriteria = "[Start] >= '09/30/2001'";             Console.WriteLine("Criteria: " + sCriteria.ToString());            oAppointment = (Outlook.AppointmentItem)oItems.Find(sCriteria);            Console.WriteLine("Used Find with Date fields");            if (oAppointment is Outlook.AppointmentItem)                Console.WriteLine("Found -> " + oAppointment.Subject.ToString());            else               Console.WriteLine("No object found");            // Log off            oNS.Logoff();            // Clean up            oAppointment = null;            oRestrictedItems = 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;      }   }}
  6. Procure a cadeia de texto TODO no código e, em seguida, modifique o código do seu ambiente.

  7. Prima a tecla F5 para criar e executar o programa.

Referências

Para obter mais informações sobre as funcionalidades de segurança do Outlook 2002, clique no número de artigo seguinte para ver o artigo na Base de Dados de Conhecimento Microsoft:

290500 Descrição das funcionalidades de segurança de e-mail relacionadas com os programadores no Outlook 2002Para obter informações adicionais sobre problemas que podem ocorrer quando utiliza a propriedade Contar de grandes coleções, clique no seguinte número de artigo para ver o artigo na Base de Dados de Conhecimento Microsoft:

294385 OL2002: propriedade Contar incorretamente com compromissos periivos

Precisa de mais ajuda?

Quer mais opções?

Explore os benefícios da subscrição, navegue em cursos de formação, saiba como proteger o seu dispositivo e muito mais.