通过MS Graph API向Teams聊天发附件:接收者无权限打开文件
问题:通过MS Graph API发送Teams带附件消息,接收者无法打开文件(权限问题)
我通过MS Graph API发送包含附件的Teams聊天消息,流程能正常执行,但接收者无法打开文件(疑似权限问题)。我参考了微软官方文档的示例代码,当前流程是:
- 通过
POST /me/drive/items/{parent-id}:/{filename}:/content将文件上传到个人OneDrive - 通过
POST /chats/{chat-id}/messages发送消息,请求体如下:
{ "body": { "content": "here is the file <attachment id=\"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx\"></attachment>", "contentType": "html" }, "attachments": [{ "id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "contentType": "reference", "name": "docker-compose.yml", "contentUrl": "https://xxx-my.sharepoint.com/personal/xxx_onmicrosoft_com/Documents/docker-compose.yml" }] }
请问问题出在哪里?
问题根源
你上传文件到个人OneDrive后,该文件默认仅你本人拥有访问权限,Teams聊天中的接收者没有权限访问这个私有文件,因此无法打开。
解决方案
你需要在发送消息前,为聊天中的成员授予文件的读取权限,或者生成一个允许组织内/特定用户访问的共享链接,替代原有的私有文件链接。
方案1:为聊天成员授予文件读取权限
在上传文件后,调用POST /me/drive/items/{file-item-id}/invite API,给聊天中的所有成员添加读取权限:
POST https://graph.microsoft.com/v1.0/me/drive/items/{file-item-id}/invite Content-Type: application/json { "recipients": [ { "email": "user1@contoso.com" }, { "email": "user2@contoso.com" } ], "message": "请访问此附件", "requireSignIn": true, "sendInvitation": false, "roles": ["read"] }
recipients:填写聊天中所有接收者的邮箱sendInvitation:设为false不会发送邮件通知,仅静默添加权限roles:设为read授予读取权限
方案2:生成组织内可访问的共享链接
调用POST /me/drive/items/{file-item-id}/createLink API生成共享链接,然后将contentUrl替换为生成的链接:
POST https://graph.microsoft.com/v1.0/me/drive/items/{file-item-id}/createLink Content-Type: application/json { "type": "view", "scope": "organization" }
返回结果中的webUrl就是组织内所有用户都能访问的链接,将其替换到消息请求体的contentUrl中即可。
方案3:上传文件到团队共享文档库
如果是团队聊天,可以将文件上传到团队对应的SharePoint文档库(而非个人OneDrive),团队成员默认拥有该库的访问权限。上传API改为:
POST https://graph.microsoft.com/v1.0/groups/{team-group-id}/drive/items/{parent-folder-id}:/{filename}:/content
然后用该文件的链接作为contentUrl即可。
注意事项
- 确保你的Graph API权限包含
Files.ReadWrite和ChatMessage.Send,且已正确完成授权 - 一对一聊天优先选择方案1或2;团队聊天优先选择方案3,更符合协作场景
内容的提问来源于stack exchange,提问作者Dominik
相关产品推荐
相关产品推荐

