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

求displayNewMessageForm与addFileAttachmentFromBase64Async结合使用示例

实现步骤与示例代码

1. 下载受保护文件并转换为Base64

先实现工具函数,从受保护URL下载文件并转为Base64格式(需根据实际权限机制添加认证信息):

async function downloadFileToBase64(fileUrl) {
  // 替换为实际的认证逻辑,比如添加Authorization头
  const response = await fetch(fileUrl, {
    headers: {
      'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
    }
  });
  
  if (!response.ok) {
    throw new Error(`文件下载失败: ${response.statusText}`);
  }
  
  const blob = await response.blob();
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result.split(',')[1]); // 移除data URL前缀
    reader.onerror = reject;
    reader.readAsDataURL(blob);
  });
}

2. 打开新邮件窗体并添加附件

核心逻辑是通过ItemChanged事件捕获新打开的撰写窗体实例,再调用addFileAttachmentFromBase64Async添加附件:

async function createNewMailWithAttachment() {
  try {
    // 1. 提前下载文件并转为Base64
    const fileBase64 = await downloadFileToBase64('https://your-protected-file-url.docx');
    
    // 2. 打开新邮件撰写窗体
    Office.context.mailbox.displayNewMessageForm({
      subject: '带附件的测试邮件',
      toRecipients: ['test@example.com']
    });
    
    // 3. 注册事件监听,捕获新激活的邮件项
    let itemChangedHandler;
    itemChangedHandler = async function(eventArgs) {
      const newMailItem = Office.context.mailbox.item;
      
      // 确认是新创建的撰写窗体
      if (newMailItem.itemType === Office.MailboxEnums.ItemType.Message && newMailItem.isNew) {
        // 4. 添加Base64格式的附件
        newMailItem.addFileAttachmentFromBase64Async(
          fileBase64,
          '测试文档.docx',
          { isInline: false },
          function(asyncResult) {
            if (asyncResult.status === Office.AsyncResultStatus.Failed) {
              console.error('添加附件失败:', asyncResult.error.message);
            } else {
              console.log('附件添加成功');
            }
            
            // 清理事件监听,避免后续误触发
            Office.context.mailbox.removeHandlerAsync(Office.EventType.ItemChanged, { handler: itemChangedHandler });
          }
        );
      }
    };
    
    Office.context.mailbox.addHandlerAsync(Office.EventType.ItemChanged, itemChangedHandler);
    
  } catch (error) {
    console.error('操作失败:', error.message);
  }
}

关键注意事项

  • 事件监听必要性:displayNewMessageForm是异步操作,无法直接返回新窗体实例,必须通过ItemChanged事件捕获新激活的邮件项。
  • 新窗体校验:通过isNew属性确认当前操作的是新创建的撰写窗体,避免误修改已有邮件。
  • 认证适配:下载受保护文件时,需根据实际权限体系调整请求头(如Bearer令牌、Cookie等)。
  • 监听清理:附件添加完成后必须移除事件监听,防止后续切换邮件时重复执行逻辑。

内容的提问来源于stack exchange,提问作者S Huff

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 14:05:00