如何在发送前更新 outlook 邮件正文文本

How to update outlook mail body text before sending

我正在开发一个 Outlook 加载项来处理电子邮件附件,方法是将它们放在服务器上并在电子邮件中放入 URL。

一个问题是,在将 URL 添加到电子邮件正文的末尾后,用户的光标会重置到电子邮件的开头。

一个相关的问题是我不知道光标在文本中的什么位置,所以我无法将 URL 插入正确的位置。

这里有一些代码展示了我在做什么,为简单起见,代码假设正文是纯文本。


 private void MyAddIn_Startup(object sender, System.EventArgs e)
    {

        Application.ItemLoad += new Outlook.ApplicationEvents_11_ItemLoadEventHandler(Application_ItemLoad);
    }

   void Application_ItemLoad(object Item)
    {

        currentMailItem = Item as Outlook.MailItem;

        ((Outlook.ItemEvents_10_Event)currentMailItem).BeforeAttachmentAdd += new Outlook.ItemEvents_10_BeforeAttachmentAddEventHandler(ItemEvents_BeforeAttachmentAdd);


    }
void ItemEvents_BeforeAttachmentAdd(Outlook.Attachment attachment, ref bool Cancel)
    {
        string url = "A URL";
        if (currentMailItem.BodyFormat == Outlook.OlBodyFormat.olFormatHTML)
        {
            // code removed for clarity
        }
        else if (currentMailItem.BodyFormat == Outlook.OlBodyFormat.olFormatRichText)
        {
            // code removed for clarity
        }
        else
            currentMailItem.Body += attachment.DisplayName + "<" + url + ">";

       Cancel = true;
    }

使用Application.ActiveInspector.WordEditor检索Word文档对象。使用 Word 对象模型执行所有更改。

这似乎符合我的要求:

using Microsoft.Office.Interop.Word;
    void ItemEvents_BeforeAttachmentAdd(Outlook.Attachment attachment, ref bool Cancel)
    {
         if (attachment.Type == Outlook.OlAttachmentType.olByValue)
        {
            string url = "A URL";
             Document doc = currentMailItem.GetInspector.WordEditor;
            Selection objSel = doc.Windows[1].Selection;
            object missObj = Type.Missing;

            doc.Hyperlinks.Add(objSel.Range, url, missObj, missObj, attachment.DisplayName, missObj);

            Cancel = true;
        }
    }