使用 Office Interop 启动 Outlook 时出现问题

Issue launching Outlook using Office Interop

我正在用 C# 构建一个 ASP webforms 应用程序,我正在尝试启动 Outlook 以从客户端计算机发送电子邮件。

我正在使用我在网上找到的以下示例。

    public void sendEmail(object sender, EventArgs e)

{

        // Create the Outlook application.
        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);

        // Create a new mail item.
        Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

        // Set HTMLBody. 
        oMsg.HTMLBody = "Test";

        //Subject line
        oMsg.Subject = "Test Subject";

        // Add a recipient.
        Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;

        // Change the recipient in the next line if necessary.
        Outlook.Recipient oRecip;

        oRecip = (Outlook.Recipient)oRecips.Add("yyyyy@mydomain.co.uk");
        oRecip.Resolve();

        // Send.
        oMsg.Send();

        //Log off.
        oNS.Logoff();
    }

我在这行代码中遇到问题:

oNS.Logon(Missing.Value, Missing.Value, false, true);

即使我配置了 Outlook 配置文件,当它运行这行代码时,我的应用程序也会启动 Outlook 并显示 "Welcome to Outlook 2016" 对话框。

预期的行为是使用现有配置文件启动 Outlook。

如果 Outlook 已经打开,我会收到一条错误消息:

System.Runtime.InteropServices.COMException: 'Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)).'

预期的行为是,如果 Outlook 已经打开,我的应用程序将使用现有的 Outlook 进程。

非常感谢任何帮助。

Microsoft 目前不推荐也不支持来自任何无人值守、非交互式客户端应用程序或组件(包括 ASP、ASP.NET、DCOM 和 NT)的 Microsoft Office 应用程序自动化服务),因为当 Office 在此环境中 运行 时,Office 可能表现出不稳定的行为 and/or 死锁。

如果您要在服务器端上下文中构建 运行 的解决方案,您应该尝试使用已针对无人值守执行安全处理的组件。或者,您应该尝试找到至少允许 运行 客户端部分代码的替代方案。如果您从服务器端解决方案使用 Office 应用程序,该应用程序将缺少许多 运行 成功所必需的功能。此外,您将承担整体解决方案稳定性的风险。在 Considerations for server-side Automation of Office 文章中阅读更多相关信息。

作为一种可能的解决方法,您可以考虑 Outlook 基于的低级别 API - Extended MAPI。或者只是围绕 API 的任何包装器,例如 Redemption。

如果您只处理 Exchange 配置文件,您可以考虑使用 Exchange Web 服务 (EWS),请参阅 Start using web services in Exchange