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

如何通过Microsoft Graph向Teams频道发送公告类型聊天消息

问题根因

你遇到这个报错是三个配置错误导致的,和附件ID只读的说法没有关系:

  • Attachments 参数要求传入数组类型,你原代码里传的是单个哈希表对象,接口无法正确解析附件的顶层结构
  • 附件ID是附件对象的顶层属性,和contentType、content平级,你原代码里把id注释/放在了content子对象内部,接口识别不到
  • 公告附件的ID不需要系统生成,你自己生成随机GUID即可,只要保证附件对象的id值,和HTML正文里<attachment>标签的id属性值完全一致就可以正常识别。
修正后的PowerShell(Microsoft.Graph模块)实现
Select-MgProfile beta
Connect-MgGraph -Scopes "ChannelMessage.Send"

# 生成随机GUID作为附件匹配ID
$announcementAttachmentId = [guid]::NewGuid().ToString()

# 注意Attachments是数组,id放在附件对象顶层
$attachments = @(
    @{
        id          = $announcementAttachmentId
        contentType = "application/vnd.microsoft.teams.messaging-announcementBanner"
        content     = @{
            title            = "This is an important announcement"
            cardImageType    = "colorTheme"
            cardImageDetails = @{
                colorTheme = "periwinkleBlue"
            } | ConvertTo-Json -Compress
        }
    }
)

$bodyContent = @"
<attachment id="$announcementAttachmentId"></attachment>
<div>Hi all, 这里填写公告正文内容</div>
"@

$params = @{
    ChannelId   = "替换为实际频道ID"
    TeamId      = "替换为实际团队ID"
    Attachments = $attachments
    Importance  = "high"
    Body        = @{
        ContentType = "html"
        Content     = $bodyContent
    }
}

New-MgTeamChannelMessage @params
原生REST接口调用示例

如果不用PowerShell模块,可以直接向beta版Graph接口发POST请求,请求地址为https://graph.microsoft.com/beta/teams/{team-id}/channels/{channel-id}/messages,请求体结构如下:

{
    "importance": "high",
    "body": {
        "contentType": "html",
        "content": "<attachment id=\"e5718d51-22a3-4c28-9978-1f3aexample\"></attachment><div>Hi all, 公告正文内容</div>"
    },
    "attachments": [
        {
            "id": "e5718d51-22a3-4c28-9978-1f3aexample",
            "contentType": "application/vnd.microsoft.teams.messaging-announcementBanner",
            "content": "{\"title\":\"This is an important announcement\",\"cardImageType\":\"colorTheme\",\"cardImageDetails\":\"{\\\"colorTheme\\\":\\\"periwinkleBlue\\\"}\"}"
        }
    ]
}
补充说明
  • 内置可选的公告主题色除了periwinkleBlue,还支持red、green、orange、purple、darkBlue
  • 如果需要使用自定义图片作为公告头图,把cardImageType改为uploadedImage,在cardImageDetails中传入图片的托管URL、宽高参数即可
  • 公告类型消息目前仅在beta版本Graph中支持,v1.0版本暂未开放对应能力
  • 权限除了委派权限ChannelMessage.Send,使用应用权限ChannelMessage.Send.All也可正常调用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 16:33:41