Outlook VSTO(C#)中mailItem.GetInspector.WordEditor返回错误邮件正文问题
Outlook VSTO(C#)导出邮件PDF时WordEditor内容异常问题
我正在编写Outlook VSTO(C#)脚本,用于导出邮件附件及将邮件导出为PDF,要求PDF包含发件人、收件人、主题、附件等信息,与直接打印PDF内容一致。
由于Outlook VSTO无直接导出PDF的方法,因此采用先将邮件保存为Word文档再自行补充信息的方案。代码逻辑为遍历选中的每个MailItem,传入CustomMailItem类处理导出。初期运行正常,但在处理某些加载耗时较长的邮件时,inspector.WordEditor返回的始终是选中的第一封邮件的正文,而CustomMailItem中的mailItem对象是正确的(邮件头及.msg导出正常)。尝试使用Thread.Sleep、inspector.Display()及Activate()均无法解决加载问题。
核心代码
主函数代码(已移除无关部分)
private void exportAllSelected_Click(object sender, EventArgs e) { CustomMailItem thisCustomMailItem = null; Word.Application wordApp = null; int maxItems = 0; int currentIndex = 0; try { #region Initialise GetExportOptions(); if (exportOptions.word || exportOptions.pdf) { wordApp = new Word.Application(); wordApp.Visible = true; //Debug only } #endregion // Run with background worker and progress bar ProgressHelper.RunWithProgress((worker, progressTracker) => { #region Explorer progressTracker.UpdateStatus($"Getting mail items"); Application outlookApp = Globals.ThisAddIn.Application; Explorer explorer = outlookApp.ActiveExplorer(); maxItems = explorer.Selection.Count; #endregion foreach (object item in explorer.Selection) { MailItem mailItem = null; try { //Checks to skip non MailItems #region Export thisCustomMailItem = new CustomMailItem(mailItem, exportOptions, wordApp); thisCustomMailItem.ExportAll(); #endregion } catch (Exception ex) { // Log Error if required } finally { if (mailItem != null) { Marshal.ReleaseComObject(mailItem); } if (thisCustomMailItem != null) { thisCustomMailItem.ReleaseItems(); } } } }); } catch (Exception ex) { // Log Error if required } finally { if (thisCustomMailItem != null) { thisCustomMailItem.ReleaseItems(); } if (wordApp != null) { wordApp.Quit(); Marshal.FinalReleaseComObject(wordApp); wordApp = null; } } }
CustomMailItem类相关代码
Word.Document tempDoc; Inspector inspector; private void GetWordDoc() { #region Save word document from mailItem inspector = mailItem.GetInspector; System.Threading.Thread.Sleep(100); if (!(inspector.IsWordMail() && inspector.EditorType == OlEditorType.olEditorWord)) { throw new Exception("Selected item is not word mail"); } Word.Document oDoc = inspector.WordEditor; bool isODocNull = oDoc == null; oDoc.SaveAs2(paths.word); System.Threading.Thread.Sleep(100); #region Discard Marshal.FinalReleaseComObject(oDoc); oDoc = null; inspector.Close(OlInspectorClose.olDiscard); Marshal.FinalReleaseComObject(inspector); inspector = null; #endregion #endregion #region Format Word Doc RetryForBusy(() => { tempDoc = wordApp.Documents.Open(paths.word); }); // Manual inspection shows the contents of this document defaults to the first email in selection at some point. // Do other operations with Word Doc Here (e.g. add sender, subject, export as PDF) #endregion }
内容的提问来源于stack exchange,提问作者ZQ G
相关产品推荐
相关产品推荐

