【问题标题】:Retrieve Current Email Body In Outlook在 Outlook 中检索当前电子邮件正文
【发布时间】:2012-06-11 17:33:44
【问题描述】:

在我的 Outlook 插件中,我想在功能区上添加一个按钮,因此当用户单击此按钮时,我想检索当前选定电子邮件的正文,我有此代码,但它只检索收件箱中的第一封电子邮件,因为索引是1:

Microsoft.Office.Interop.Outlook.Application myApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace mapiNameSpace = myApp.GetNamespace("MAPI");
Microsoft.Office.Interop.Outlook.MAPIFolder myInbox = mapiNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
String body = ((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[1]).Body;

那么如何在 Outlook 中检索当前打开的电子邮件? ,这种方法对我有用,但我需要获取当前电子邮件的索引。

谢谢。

【问题讨论】:

    标签: c# outlook-addin outlook-2007 outlook-2010


    【解决方案1】:

    您不应该每次都初始化一个新的 Outlook.Application() 实例。大多数加载项框架为您提供了一个 Outlook.Application 实例,对应于当前的 Outlook 会话,通常通过名为 Application 的字段或属性。您应该在加载项的整个生命周期内使用它。

    要获取当前选择的项目,请使用:

    Outlook.Explorer explorer = this.Application.ActiveExplorer();
    Outlook.Selection selection = explorer.Selection;
    
    if (selection.Count > 0)   // Check that selection is not empty.
    {
        object selectedItem = selection[1];   // Index is one-based.
        Outlook.MailItem mailItem = selectedItem as Outlook.MailItem;
    
        if (mailItem != null)    // Check that selected item is a message.
        {
            // Process mail item here.
        }
    }
    

    请注意,上面将让您处理 first 选定的项目。如果您选择了多个项目,您可能希望循环处理它们。

    【讨论】:

    • 感谢帮助,但第 2 行出现错误:Non-invocable member 'Microsoft.Office.Interop.Outlook._Explorer.Selection' 不能像方法一样使用
    • 道歉;我忘了Selection 是一个属性,而不是一个方法。使用修改后的代码重试。
    • 可以添加检查所选项目是否为邮件项目以及用户可能选择了联系人、约会或其他内容。只是我的 2 美分。
    • @PavelDonchev:检查已在执行。如果as MailItem 转换失败,则mailItem 将包含null
    【解决方案2】:

    在顶部添加参考

    using Outlook = Microsoft.Office.Interop.Outlook;
    

    然后在方法内部;

    Outlook._Application oApp = new Outlook.Application();
    if (oApp.ActiveExplorer().Selection.Count > 0)
                {
                    Object selObject = oApp.ActiveExplorer().Selection[1];
    
                    if (selObject is Outlook.MailItem)
                    {
                        Outlook.MailItem mailItem = (selObject as Outlook.MailItem);
                        String htmlBody = mailItem.HTMLBody;
                        String Body = mailItem.Body;
                     }
                 }
    

    您还可以在查看邮件之前更改将在 Outlook 中显示的正文。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-22
      • 1970-01-01
      • 1970-01-01
      • 2013-02-11
      • 1970-01-01
      • 2010-11-20
      • 1970-01-01
      • 2015-06-04
      相关资源
      最近更新 更多