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

如何使用JavaScript或Graph API将邮件从个人邮箱迁移至共享邮箱任意文件夹

用JavaScript通过Graph API实现邮件移动/复制到共享邮箱

下面是基于Microsoft Graph API的解决方案,这是微软官方推荐的现代邮箱操作方案,支持移动、复制单个邮件以及批量迁移收件箱邮件到共享邮箱。

前置准备

  1. 注册Azure AD应用,获取客户端ID、租户ID,并配置相应权限:
    • 前端交互式场景:添加Mail.ReadWrite委派权限,需用户授权访问个人邮箱和共享邮箱
    • 后台服务场景:添加Mail.ReadWrite.All应用权限,同时需给应用授予共享邮箱的访问权限(Azure门户或PowerShell配置)
  2. 安装依赖(若使用Graph SDK):
    npm install @microsoft/microsoft-graph-client @azure/msal-browser
    
  3. 初始化Graph客户端,确保已获取有效的访问令牌(可通过MSAL库实现身份验证)。

1. 移动单个邮件到共享邮箱指定文件夹

调用Graph API的move端点,指定目标共享邮箱和文件夹ID:

// 假设已初始化Graph客户端(getGraphClient为自定义初始化函数)
const graphClient = getGraphClient();

async function moveEmail(emailId, sharedMailboxAddr, targetFolderId) {
  try {
    await graphClient.api(`/me/messages/${emailId}/move`)
      .post({
        destinationId: targetFolderId, // 共享邮箱内目标文件夹的ID
        mailboxId: sharedMailboxAddr   // 共享邮箱的完整邮箱地址
      });
    console.log(`邮件 ${emailId} 移动成功`);
  } catch (err) {
    console.error(`移动失败: ${err.message}`);
  }
}

如何获取共享邮箱文件夹ID?调用/users/{sharedMailboxAddr}/mailFolders接口,返回的列表中包含每个文件夹的id字段。


2. 复制单个邮件到共享邮箱指定文件夹

与移动逻辑类似,改用copy端点:

async function copyEmail(emailId, sharedMailboxAddr, targetFolderId) {
  try {
    await graphClient.api(`/me/messages/${emailId}/copy`)
      .post({
        destinationId: targetFolderId,
        mailboxId: sharedMailboxAddr
      });
    console.log(`邮件 ${emailId} 复制成功`);
  } catch (err) {
    console.error(`复制失败: ${err.message}`);
  }
}

3. 批量迁移个人收件箱邮件到共享邮箱

由于收件箱可能有大量邮件,需分页获取并批量处理,避免请求超限:

async function migrateInboxToShared(sharedMailboxAddr, targetFolderId) {
  let nextPageLink = "/me/mailFolders/inbox/messages?$select=id"; // 仅获取邮件ID,减少数据传输
  let totalMigrated = 0;

  while (nextPageLink) {
    try {
      const res = await graphClient.api(nextPageLink).get();
      const emailIds = res.value.map(item => item.id);

      // 逐批处理(建议每批20-50条,避免触发Graph API速率限制)
      for (const id of emailIds) {
        await moveEmail(id, sharedMailboxAddr, targetFolderId);
        // 若需复制而非移动,替换为copyEmail(id, sharedMailboxAddr, targetFolderId)
        totalMigrated++;
      }

      nextPageLink = res["@odata.nextLink"]; // 获取下一页链接
    } catch (err) {
      console.error(`迁移中断: ${err.message}`);
      break;
    }
  }
  console.log(`迁移完成,共处理 ${totalMigrated} 封邮件`);
}

注意:Graph API有请求速率限制,若批量处理量极大,建议添加适当延迟(如await new Promise(resolve => setTimeout(resolve, 1000)))避免被限流。


替代方案(不推荐优先使用)

若无法使用Graph API,可考虑Exchange Web Services(EWS),通过SOAP请求调用MoveItem或CopyItem操作,但EWS已进入维护阶段,微软不再新增功能,且JavaScript实现复杂度远高于Graph API,仅作为临时备选。

内容的提问来源于stack exchange,提问作者Zia ul Qamar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.01 23:54:51