【问题标题】:Automate Sending an email through Microsoft Outlook通过 Microsoft Outlook 自动发送电子邮件
【发布时间】:2015-03-26 04:48:56
【问题描述】:

我是 C# 的新手,我正在尝试通过以下代码自动从 Outlook 发送电子邮件,它在开发环境中运行良好。即使没有打开 Outlook,我也希望它使用默认用户作为发件人。

        private void EmailMessage(string recipient, string subject, string body)
    {
        Microsoft.Office.Interop.Outlook.Application application = new Microsoft.Office.Interop.Outlook.Application();
        Microsoft.Office.Interop.Outlook.MailItem email = (Outlook.MailItem)application.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);

        try
        {
            email.Subject = subject;
            email.Body = body;
            email.To = recipient;
            ((Outlook._MailItem)email).Send();
            _emailConfirmation = true;
        }

        catch (System.Runtime.InteropServices.COMException ex)
        {
            Logging.LogError("Trip Email Failed", ExceptionHelper.GetInnerMostException(ex));
            _emailConfirmation = false;
        }

        finally
        {
            //release the objects used to send email after message has been sent\\
            if (email != null)
                System.Runtime.InteropServices.Marshal.ReleaseComObject(email);
            if (application != null)
                System.Runtime.InteropServices.Marshal.ReleaseComObject(application);
        }
    }

所有用户都分配了一个帐户并安装了带有有效防病毒软件的 Outlook。我担心的是,当它上线时,它会在创建新的前景实例或其他我没有看到的东西时失败。您认为这将与我打算在它上线后完成的工作相一致吗?

代码没有错误,但是我看到很多人说你不应该直接创建outlook.application的实例。

https://msdn.microsoft.com/en-us/library/office/bb622502.aspx

我想我可能只是偏执,因为我以前从未使用过 PIA

【问题讨论】:

  • 我不确定你在问什么......它在你的开发环境中对你有用吗?如果没有,出了什么问题?
  • 确切的错误是什么?
  • 代码没有错误,但是我看到很多人说你不应该直接创建outlook.application的实例。 msdn.microsoft.com/en-us/library/office/bb622502.aspx 我想我可能只是偏执,因为我以前从未使用过 PIA
  • 我没有在代码中看到任何奇怪的地方。请参阅sample code 了解更多信息。

标签: c# outlook interop


【解决方案1】:

您的代码失败可能有两个主要原因:

  1. 您遇到了安全问题。请参阅Outlook "Object Model Guard" Security Issues for Developers,了解有关此问题的更多信息以及弥合差距并抑制或避免此类问题的可能方法。请注意,在某些情况下,对话窗口不会显示给用户,您只是在代码中遇到了异常。

  2. Office 2010 的 Click2Run 版本不支持自动化。有关更多信息,请参阅Office 2010 Click-to-Run compatibility with add-ins。您还可以找到How to: Verify Whether Outlook Is a Click-to-Run Application on a Computer 文章。

尝试使用收件人属性而不是收件人字段。然后使用 Resolve 或 ResolveAll 方法。请参阅How To: Fill TO,CC and BCC fields in Outlook programmatically 了解更多信息。

我还建议在代码中添加任何日志记录机制。因此,您可以分析日志文件并了解幕后情况。例如,考虑使用 log4net 库。

【讨论】:

  • 感谢您的意见。我将尝试使用 Recipient 代替 To 方法。除了验证收件人是有效帐户之外,使用收件人而不是收件人是否有优势?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-15
  • 2021-12-28
  • 2011-09-14
  • 2012-03-03
  • 1970-01-01
  • 2016-12-28
相关资源
最近更新 更多