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

SharePoint 365 (在线版) 插入代码片段显示 Outlook 365 未读邮件数咨询

SharePoint Online 展示 Outlook 未读邮件数量实现方案

要实现这个需求,核心是调用Microsoft Graph API查询收件箱未读邮件计数,再把结果渲染到SharePoint页面上,下面是两种可直接使用的实现方式:

方式1:脚本编辑器快速实现(适合测试场景)

先确保你的SharePoint站点已经开启自定义脚本运行权限,之后往页面添加「脚本编辑器」Web部件,粘贴以下代码即可:

<script src="https://alcdn.msauth.net/browser/2.38.0/js/msal-browser.min.js"></script>
<div id="unread-count-container" style="font-size: 16px; padding: 10px;">
  未读邮件:<span id="unread-count" style="color: #ff0000; font-weight: bold;">加载中...</span>
</div>
<script>
const msalConfig = {
  auth: {
    clientId: "你注册的Azure AD应用客户端ID",
    authority: "https://login.microsoftonline.com/你的租户ID",
    redirectUri: window.location.origin
  }
};
const msalInstance = new msal.PublicClientApplication(msalConfig);
const loginRequest = { scopes: ["Mail.Read"] };

async function getUnreadCount() {
  try {
    const response = await msalInstance.acquireTokenSilent(loginRequest);
    const graphRes = await fetch("https://graph.microsoft.com/v1.0/me/mailFolders/Inbox/messages?$filter=isRead eq false&$count=true", {
      headers: { Authorization: `Bearer ${response.accessToken}`, ConsistencyLevel: "eventual" }
    });
    const data = await graphRes.json();
    document.getElementById("unread-count").innerText = data["@odata.count"] || 0;
  } catch (err) {
    // 静默获取失败则主动弹窗授权
    await msalInstance.loginPopup(loginRequest);
    getUnreadCount();
  }
}

msalInstance.initialize().then(() => {
  getUnreadCount();
});
</script>

前置配置要求

  • 在Azure AD中注册单页应用,重定向URI填写你的SharePoint站点根域名,授予该应用Mail.Read委托权限
  • 替换代码中的clientId和租户ID为你自己的租户对应参数

方式2:SPFx Web部件实现(生产环境推荐)

官方推荐的生产级方案,无需单独注册Azure AD应用,直接在SPFx项目中声明权限即可调用。

核心代码片段

  1. 首先在package-solution.json中添加权限声明:
"webApiPermissionRequests": [
  {
    "resource": "Microsoft Graph",
    "scope": "Mail.Read"
  }
]
  1. 在Web部件代码中调用Graph API获取未读计数:
protected async onInit(): Promise<void> {
  const graphClient = await this.context.msGraphClientFactory.getClient("3");
  const res = await graphClient
    .api("/me/mailFolders/Inbox/messages")
    .filter("isRead eq false")
    .count(true)
    .header("ConsistencyLevel", "eventual")
    .get();
  this.unreadCount = res["@odata.count"] || 0;
  return super.onInit();
}

部署要求

  • 打包部署SPFx包到SharePoint应用目录后,需要租户管理员在SharePoint admin中心同意对应的Graph权限请求,功能即可正常使用
  • 该方案权限隔离更安全,兼容所有现代SharePoint站点,也支持适配移动端显示

注意事项

  • 两种方案均只会获取当前登录用户自己的未读邮件数据,不会访问其他用户的邮箱内容
  • 不要申请超出需求的邮箱权限,避免带来不必要的安全风险

内容的提问来源于stack exchange,提问作者Jo De Pelsmaeker

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 08:57:03