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
相关产品推荐
相关产品推荐

