You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#开发Outlook VSTO插件如何获取阅读窗格中预览的邮件?

解决方案

核心原理

  • Outlook 中独立打开的邮件窗口对应 Inspector 对象,包含邮件列表、阅读窗格的主界面对应 Explorer 对象
  • 阅读窗格当前预览的邮件,就是主界面选中列表的首个 MailItem 对象

兼容双场景的实现代码

using Microsoft.Office.Interop.Outlook;
using System.Runtime.InteropServices;

// ......

MailItem targetMail = null;
Inspector activeInspector = null;
Explorer activeExplorer = null;

try
{
    // 优先读取独立窗口打开的邮件
    activeInspector = Globals.ThisAddIn.Application.ActiveInspector();
    if (activeInspector != null && activeInspector.CurrentItem is MailItem inspectorMail)
    {
        targetMail = inspectorMail;
    }
    else
    {
        // 无独立窗口时读取阅读窗格预览的邮件
        activeExplorer = Globals.ThisAddIn.Application.ActiveExplorer();
        if (activeExplorer != null && activeExplorer.Selection.Count > 0)
        {
            object selectedItem = activeExplorer.Selection[1];
            if (selectedItem is MailItem explorerMail)
            {
                targetMail = explorerMail;
            }
        }
    }

    if (targetMail != null)
    {
        // 你的原有业务逻辑:保存邮件、打包为附件发送等
        string path = @"C:\Test\Mail.msg";
        targetMail.SaveAs(path, OlSaveAsType.olMSG);
        // 后续发送新邮件的逻辑写在此处
    }
}
finally
{
    // 手动释放COM对象避免内存泄漏
    if (targetMail != null) Marshal.ReleaseComObject(targetMail);
    if (activeInspector != null) Marshal.ReleaseComObject(activeInspector);
    if (activeExplorer != null) Marshal.ReleaseComObject(activeExplorer);
}

注意事项

  • 如果需要支持多选邮件批量作为附件,遍历 activeExplorer.Selection 集合的所有元素,筛选出类型为 MailItem 的对象即可
  • 代码执行前需要确保项目已经正确引用 Outlook Interop 程序集

内容的提问来源于stack exchange,提问作者Akkarin_Martell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 12:06:04