Поделиться через


Использование библиотеки объектов Microsoft Outlook для получения сообщения с помощью Visual C# из папки "Входящие"

Введение

В этой статье описывается, как использовать библиотеку объектов Microsoft Outlook 2002 или библиотеку объектов Microsoft Office Outlook 2003 для получения сообщения из папки "Входящие" с помощью Microsoft Visual C#.

Дополнительные сведения

Чтобы использовать библиотеку объектов Outlook 2002 или библиотеку объектов Outlook 2003 для получения сообщения из папки "Входящие" с помощью Visual C#, выполните следующие действия:

  1. В Microsoft Visual Studio .NET или Visual Studio 2005 создайте проект консольного приложения:

    1. В меню "Файл" наведите указатель мыши на "Создать" и выберите "Проект".

    2. В разделе "Типы проектов" выберите "Проекты Visual C#".

      Замечание

      В Visual Studio 2005 выберите Visual C#.

    3. В разделе "Шаблоны" выберите консольное приложение.

    4. Нажмите кнопку "ОК". По умолчанию создается файл с именем Class1.cs .

      Замечание

      В Visual Studio 2005 Program.cs создается по умолчанию.

  2. Добавьте ссылку на библиотеку объектов Outlook 2002 или библиотеку объектов Outlook 2003. Для этого выполните следующие действия.

    1. В меню "Проект" выберите "Добавить ссылку".

    2. Выберите вкладку COM .

    3. На вкладке COM выберите библиотеку объектов Microsoft Outlook 11.0 , если вы используете Outlook 2003, или выберите библиотеку объектов Microsoft Outlook 10.0 , если вы используете Outlook 2002.

    4. Нажмите кнопку "Выбрать".

    5. В диалоговом окне "Добавление ссылок" нажмите кнопку "ОК".

      Замечание

      Если вы получите сообщение, чтобы создать оболочки для выбранных библиотек, нажмите кнопку "Да".

  3. В окне кода Class1.cs замените весь существующий код следующим кодом:

    using System;
    using System.Reflection; // to use Missing.Value
    
    //TO DO: If you use the Microsoft Outlook 11.0 Object Library, uncomment the following line.
    //using Outlook = Microsoft.Office.Interop.Outlook;
    
    namespace ConsoleApplication1
    {
    public class Class1
    {
    public static int Main(string[]args)
    {
    try
    {
    // Create the Outlook application.
    // in-line initialization
    Outlook.Application oApp = new Outlook.Application();
    
    // Get the MAPI namespace.
    Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
    
    // Log on by using the default profile or existing session (no dialog box).
    oNS.Logon(Missing.Value,Missing.Value,false,true);
    
    // Alternate logon method that uses a specific profile name.
    // TODO: If you use this logon method, specify the correct profile name
    // and comment the previous Logon line.
    //oNS.Logon("profilename",Missing.Value,false,true);
    
    //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;
    
    // Get the first message.
    // Because the Items folder may contain different item types,
    // use explicit typecasting with the assignment.
    Outlook.MailItem oMsg = (Outlook.MailItem)oItems.GetFirst();
    
    //Output some common properties.
    Console.WriteLine(oMsg.Subject);
    Console.WriteLine(oMsg.SenderName);
    Console.WriteLine(oMsg.ReceivedTime);
    Console.WriteLine(oMsg.Body);
    
    //Check for attachments.
    int AttachCnt = oMsg.Attachments.Count;
    Console.WriteLine("Attachments: " + AttachCnt.ToString());
    
    //TO DO: If you use the Microsoft Outlook 10.0 Object Library, uncomment the following lines.
    /*if (AttachCnt > 0) 
    {
    for (int i = 1; i <= AttachCnt; i++) 
     Console.WriteLine(i.ToString() + "-" + oMsg.Attachments.Item(i).DisplayName);
    }*/
    
    //TO DO: If you use the Microsoft Outlook 11.0 Object Library, uncomment the following lines.
    /*if (AttachCnt > 0) 
    {
    for (int i = 1; i <= AttachCnt; i++) 
     Console.WriteLine(i.ToString() + "-" + oMsg.Attachments[i].DisplayName);
    }*/
    
    //Display the message.
    oMsg.Display(true); //modal
    
    //Log off.
    oNS.Logoff();
    
    //Explicitly release objects.
    oMsg = null;
    oItems = null;
    oInbox = null;
    oNS = null;
    oApp = null;
    }
    
    //Error handler.
    catch (Exception e)
    {
    Console.WriteLine("{0} Exception caught: ", e);
    }
    
    // Return value.
    return 0;
    
    }
    }
    }
    
  4. В этом коде внесите необходимые изменения там, где вы видите комментарии "TO DO."

  5. Нажмите клавишу F5, чтобы создать и запустить программу.

Ссылки

Дополнительные сведения см. в статье "Разработка Microsoft Office с помощью Visual Studio".