如何使用 Microsoft.Office.Interop.Outlook 创建默认配置文件并启动 Outlook 客户端 (GUI)

How to create a default profile and launch outlook client(GUI) using Microsoft.Office.Interop.Outlook

我试图使用默认配置文件启动 Outlook 或使用 Microsoft.Office.Interop.Outlook 程序集文件创建默认配置文件。但是我在启动 outlook 应用程序时遇到以下错误。 错误消息:属性 "http: //schemas.microsoft.com/mapi/proptag/0x7C070102" 未知或无法找到。 我是这个大会的新手。还建议任何其他框架来实现我的目标

 Outlook.Application OutlookClient()
    {
        Outlook.Application oOutlook = null;
        Outlook.NameSpace oNS = null;
        oOutlook = new Outlook.Application();
        oNS = oOutlook.GetNamespace("MAPI");
        oNS.Logon("My profile", "myprofilepassword", false, false);
        oOutlook = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
        return oOutlook;
    }

首先,代码中不需要两次初始化Application实例对象:

oOutlook = new Outlook.Application();

oOutlook = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;

其次,没有必要使用Logon方法。

这是 MSDN 对此的说明:

Use the Logon method only to log on to a specific profile when Outlook is not already running. This is because only one Outlook process can run at a time, and that Outlook process uses only one profile and supports only one MAPI session. When users start Outlook a second time, that instance of Outlook runs within the same Outlook process, does not create a new process, and uses the same profile.

If Outlook is already running, using this method does not create a new Outlook session or change the current profile to a different one.

If Outlook is not running and you only want to start Outlook with the default profile, do not use the Logon method. A better alternative is shown in the following code example, InitializeMAPI: first, instantiate the Outlook Application object, then reference a default folder such as the Inbox. This has the side effect of initializing MAPI to use the default profile and to make the object model fully functional.

Sub InitializeMAPI ()

  ' Start Outlook.
  Dim olApp As Outlook.Application
  Set olApp = CreateObject("Outlook.Application")

  ' Get a session object. 
  Dim olNs As Outlook.NameSpace
  Set olNs = olApp.GetNamespace("MAPI")

  ' Create an instance of the Inbox folder. 
  ' If Outlook is not already running, this has the side
  ' effect of initializing MAPI.
  Dim mailFolder As Outlook.Folder
  Set mailFolder = olNs.GetDefaultFolder(olFolderInbox)

  ' Continue to use the object model to automate Outlook.
End Sub

从 Outlook 2010 开始,如果您有多个配置文件,您已将 Outlook 配置为始终使用默认配置文件,并且您使用 Logon 方法登录到默认配置文件而不提示用户,无论如何,用户都会收到选择配置文件的提示。要避免这种行为,请不要使用 Logon 方法;请改用前面 InitializeMAPI 示例中建议的解决方法。

因此,您的代码应如下所示:

Outlook.Application OutlookClient()
{
    Outlook.Application oOutlook = null;
    Outlook.NameSpace oNS = null;
    oOutlook = new Outlook.Application();

    // optional
    oNS = oOutlook.GetNamespace("MAPI");
    Outlook.MAPIFolder folderInbox = oNS.GetDefaultFolder(olFolderInbox)

    return oOutlook;
}

参见 C# app automates Outlook (CSAutomateOutlook) 示例代码。