【问题标题】:Failed to access mail object MAPI from calling function从调用函数访问邮件对象 MAPI 失败
【发布时间】:2013-02-07 10:13:57
【问题描述】:

我要访问 Outlook MAPI 文件夹并获取邮件地址。这是我的方法

 public static string GetSenderEmailAddress(Microsoft.Office.Interop.Outlook.MailItem mapiObject)
    {
        Microsoft.Office.Interop.Outlook.PropertyAccessor oPA;
        string propName = "http://schemas.microsoft.com/mapi/proptag/0x0065001F";
        oPA = mapiObject.PropertyAccessor;
        string email = oPA.GetProperty(propName).ToString();
        return email;
    }

当调用按钮单击事件时,我需要触发该方法并检索邮件地址。

按钮点击事件来了。

      private void button3_Click(object sender, RibbonControlEventArgs e)
        {

 string mailadd =  ThisAddIn.GetSenderEmailAddress(Microsoft.Office.Interop.Outlook.MailItem);
        System.Windows.Forms.MessageBox.Show(mailadd);

}

此处出现错误

Microsoft.Office.Interop.Outlook.MailItem 是一个在给定上下文中无效的“类型”

这是我的第一个插件,有谁知道如何实现这个结果?

【问题讨论】:

  • 您确定 MailItem 对象有效吗?它来自哪里?
  • 当我在按钮点击事件中调用函数时发生错误。它来自调用者函数
  • 好的,调用函数从哪里获取?
  • 哦,等一下,您并没有传递实际的 MailItem 对象,而是传递了对类型的引用。 MailItem 对象必须来自某个地方。上下文是什么?它需要从哪里来?例如。如果您需要当前选定的消息,请使用 Application.ActiveExplorer.Selection 集合。当前显示的消息可以从Application.ActiveInspector.CurrentItem等中获取。

标签: c# outlook vsto outlook-addin


【解决方案1】:

您可以使用RibbonControlEventArgs 访问Context,这将为您提供MailItem 实例。

private Outlook.MailItem GetMailItem(RibbonControlEventArgs e)
{
    // Inspector Window
    if (e.Control.Context is Outlook.Inspector)
    {
        Outlook.Inspector inspector = e.Control.Context as Outlook.Inspector;
        if (inspector == null) return null;
        if (inspector.CurrentItem is Outlook.MailItem)
            return inspector.CurrentItem as Outlook.MailItem;
    }
    // Explorer Window 
    if (e.Control.Context is Outlook.Explorer)
    {
        Outlook.Explorer explorer = e.Control.Context as Outlook.Explorer;
        if (explorer == null) return null; 
        Outlook.Selection selectedItems = explorer.Selection;
        if (selectedItems.Count != 1)  return null;  
        if (selectedItems[1] is Outlook.MailItem)
            return selectedItems[1] as Outlook.MailItem;
    }     
    return null;
}

你可以添加这个方法,然后像这样使用它......

string mailAddress = string.Empty;
Outlook.MailItem mailItem = GetMailItem(e);
if (mailItem != null)
    mailAddress =  ThisAddIn.GetSenderEmailAddress(mailItem);

【讨论】:

  • 假设 Outlook 功能区上有一个按钮。看起来 OP 有一个 Win Forms 应用程序。
猜你喜欢
  • 2018-01-11
  • 1970-01-01
  • 1970-01-01
  • 2017-01-28
  • 1970-01-01
  • 2011-10-17
  • 1970-01-01
  • 2019-12-06
  • 2019-09-03
相关资源
最近更新 更多