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

Outlook插件OnMessageSend事件与插件通信及Token传递问题咨询

Windows Outlook插件:OnMessageSend事件与插件的通信及Token传递方案

针对你遇到的OnMessageSend事件处理器无法读取插件Cookies、localStorage的问题,Office插件提供了专门的跨环境存储API来实现插件主环境和事件处理器之间的数据共享,以下是两种可行方案:

方案一:使用漫游设置(roamingSettings)存储全局Token

Office.context.roamingSettings是Office插件提供的账户级跨环境存储,支持在插件主环境和OnMessageSend事件处理器中读写,数据会绑定到用户的Office账户同步。

插件主环境存储Token

在用户授权获取Token后,将其存入漫游设置:

// 插件主环境中保存Token
Office.context.roamingSettings.set("authToken", "用户获取的Token值");
Office.context.roamingSettings.saveAsync(function(saveResult) {
  if (saveResult.status === Office.AsyncResultStatus.Succeeded) {
    console.log("Token已成功保存到漫游设置");
  } else {
    console.error("Token保存失败:", saveResult.error.message);
  }
});

OnMessageSend事件处理器读取Token

在事件触发时,直接从漫游设置中读取Token并发起请求:

function onMessageSendHandler(event) {
  const authToken = Office.context.roamingSettings.get("authToken");
  
  if (!authToken) {
    // 无Token时阻止发送或提示用户
    event.completed({ allowEvent: false });
    return;
  }

  // 向外部服务发起POST请求
  fetch("你的外部服务API地址", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${authToken}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      // 请求体参数
    })
  })
  .then(response => {
    if (response.ok) {
      event.completed({ allowEvent: true });
    } else {
      throw new Error("服务请求失败");
    }
  })
  .catch(error => {
    console.error("请求异常:", error);
    event.completed({ allowEvent: false });
  });
}

方案二:使用邮件自定义属性(Custom Properties)存储

如果Token仅需针对当前发送的邮件使用,可以将其绑定到邮件的自定义属性中,适合单邮件关联的场景。

插件主环境设置自定义属性

// 加载当前邮件的自定义属性并存储Token
Office.context.mailbox.item.loadCustomPropertiesAsync(function(loadResult) {
  if (loadResult.status === Office.AsyncResultStatus.Succeeded) {
    const customProps = loadResult.value;
    customProps.set("mailAuthToken", "用户获取的Token值");
    customProps.saveAsync(function(saveResult) {
      if (saveResult.status === Office.AsyncResultStatus.Succeeded) {
        console.log("Token已绑定到当前邮件");
      }
    });
  }
});

OnMessageSend事件处理器读取自定义属性

function onMessageSendHandler(event) {
  Office.context.mailbox.item.loadCustomPropertiesAsync(function(loadResult) {
    if (loadResult.status === Office.AsyncResultStatus.Succeeded) {
      const customProps = loadResult.value;
      const authToken = customProps.get("mailAuthToken");
      
      if (authToken) {
        // 发起POST请求逻辑同方案一
      } else {
        event.completed({ allowEvent: false });
      }
    }
  });
}

关键说明

  • OnMessageSend事件处理器运行在独立的沙箱进程中,确实无法直接访问插件主环境的浏览器存储(Cookies、localStorage),必须依赖Office官方提供的跨环境API实现数据共享。
  • 漫游设置的数据会随用户账户同步到不同设备,适合存储全局有效的授权Token;自定义属性仅绑定当前邮件,适合单邮件场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 20:05:32