【发布时间】:2017-02-17 13:58:56
【问题描述】:
我在 Outlook 资源管理器中添加了一个功能区按钮,单击该按钮会从选定的电子邮件中创建一封新电子邮件。使用 MailItem.Copy 方法可以正常工作。但我还需要将消息正文中的一些文本替换为不同的值。
问题是电子邮件可能是 HTML/RichText 格式的电子邮件,并且包含文本格式和/或图片。并且简单地替换 Body 属性中的文本值会丢失所有文本格式和图片。
所以下面的代码不行
newMailItem.Body = newMailItem.Body.Replace("Old Value", "New Value");
我还尝试将 HTML 和 RTF 值加载到 DevExpress RichEditControl 中,并使用 RichEditControl.Document.ReplaceAll 方法尝试替换出现的文本。但是 DevExpress RichEditControl 以不同的方式更改/格式化 RTF/HTML 值并导致在 MailItem 中重新设置 HTML/RTF 时消息看起来不正确。
我还尝试通过获取对 Word 文档的引用来替换文本(参见下面的代码)。但这也不起作用。
Inspector inspector = newMailItem.GetInspector;
if (inspector.IsWordMail())
{
Microsoft.Office.Interop.Word.Document wordDocument =
inspector.WordEditor as Microsoft.Office.Interop.Word.Document;
Microsoft.Office.Interop.Word.Find findObject = wordDocument.Application.Selection.Find;
findObject.ClearFormatting();
findObject.Text = "old value";
findObject.Replacement.ClearFormatting();
findObject.Replacement.Text = "new value";
object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
findObject.Execute(ref missing, ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref missing, ref missing,
ref replaceAll, ref missing, ref missing, ref missing, ref missing);
}
那么问题来了,如何替换 MailItem 正文中的文本值,并确保现有的文本格式和图片不丢失?
【问题讨论】:
标签: c# vsto outlook-addin