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

.NET 6 C#实现Outlook拖拽邮件到OneNote添加附件功能求助

解决Outlook拖拽插件添加非内嵌附件到OneNote的方案

1. 筛选邮件中的非内嵌附件

先从拖拽的邮件对象中提取并筛选出非内嵌附件:

// 从拖拽数据中获取Outlook邮件对象
if (e.Data.GetDataPresent("Outlook.Message"))
{
    Outlook.MailItem mailItem = e.Data.GetData("Outlook.Message") as Outlook.MailItem;
    foreach (Outlook.Attachment attachment in mailItem.Attachments)
    {
        // 通过附件类型和MAPI属性判断是否为非内嵌附件
        bool isInlineAttachment = attachment.Type == Outlook.OlAttachmentType.olEmbeddeditem 
                                || (attachment.PropertyAccessor != null && 
                                    (bool)attachment.PropertyAccessor.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x7FFE000B"));
        
        if (!isInlineAttachment)
        {
            // 处理该非内嵌附件
            HandleAttachment(attachment);
        }
    }
}

2. 临时保存附件到本地

OneNote添加附件需要本地文件路径,先将附件保存到临时目录:

private string SaveTempAttachment(Outlook.Attachment attachment)
{
    string tempDir = Path.GetTempPath();
    string tempFilePath = Path.Combine(tempDir, attachment.FileName);
    
    // 避免文件名重复
    if (File.Exists(tempFilePath))
    {
        tempFilePath = Path.Combine(tempDir, $"{Path.GetFileNameWithoutExtension(attachment.FileName)}_{Guid.NewGuid()}{Path.GetExtension(attachment.FileName)}");
    }
    
    attachment.SaveAsFile(tempFilePath);
    return tempFilePath;
}

3. 将附件插入OneNote页面

通过OneNote Interop把附件添加到已创建的页面中:

private void InsertAttachmentToOneNote(string targetPageId, string attachmentPath)
{
    var oneNoteApp = new Microsoft.Office.Interop.OneNote.Application();
    string pageXml = string.Empty;
    
    // 获取目标页面的XML内容
    oneNoteApp.GetPageContent(targetPageId, out pageXml, Microsoft.Office.Interop.OneNote.PageInfo.piAll);
    
    // 解析XML并构造附件节点
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(pageXml);
    XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable);
    nsManager.AddNamespace("one", "http://schemas.microsoft.com/office/onenote/2013/onenote");
    
    XmlElement attachmentNode = doc.CreateElement("one:File", "http://schemas.microsoft.com/office/onenote/2013/onenote");
    attachmentNode.SetAttribute("path", attachmentPath);
    attachmentNode.SetAttribute("displayName", Path.GetFileName(attachmentPath));
    
    // 将附件节点插入页面Body末尾
    XmlNode bodyNode = doc.SelectSingleNode("//one:Body", nsManager);
    bodyNode.AppendChild(attachmentNode);
    
    // 更新OneNote页面内容
    oneNoteApp.UpdatePageContent(doc.OuterXml);
    
    // 清理临时文件
    File.Delete(attachmentPath);
}

关键注意事项

  • 确保项目已引用Microsoft.Office.Interop.Outlook和Microsoft.Office.Interop.OneNote程序集
  • 处理大附件时建议用异步逻辑,避免UI阻塞
  • 验证临时目录的读写权限,确保附件能正常保存

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 13:47:44