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

PHP调用Microsoft Graph SDK如何获取附件的contentBytes值

PHP 调用 Microsoft Graph SDK 读取 Outlook 附件 contentBytes 正确方案

问题原因

无法读取contentBytes值是三个配置/用法错误导致的:

  • 返回类型配置错误:请求/attachments附件接口时,错误将返回类型设置为Model\Message::class,接口实际返回的是附件模型对象,和Message类型不匹配,导致类中没有封装附件字段的对应读取方法。
  • 访问方式错误:_propDict是Graph SDK模型类的受保护属性,无法在类外部直接访问,必须通过SDK提供的公共方法读取字段值。
  • 额外参数问题:请求的$expand参数前存在多余空格,可能引发接口参数解析异常。

修正步骤

  1. 修正接口请求的返回类型配置,附件接口统一使用Model\Attachment::class作为返回类型,修正后请求代码如下:
$expand = "microsoft.graph.itemattachment/item";
// 去掉$expand参数前的多余空格
$requestUrl = '/me/messages/'.$message->getId().'/attachments/?$expand='.$expand;
$attachments = $userClient->createCollectionRequest('GET', $requestUrl)
    ->setReturnType(Model\Attachment::class)
    ->setPageSize(10)
    ->getPage();
  1. 使用SDK封装的Getter方法读取字段值,遍历附件集合时先判断附件类型,再读取对应内容:
foreach ($attachments as $attachment) {
    // 处理普通文件附件
    if ($attachment->getOdataType() === '#microsoft.graph.fileAttachment') {
        // 直接调用封装方法获取contentBytes
        $contentBytes = $attachment->getContentBytes();
        // *注意:返回值为base64编码格式,解码后即为文件二进制内容,可直接写入本地存储
        $fileContent = base64_decode($contentBytes);
        // 示例:以附件原文件名保存到本地
        file_put_contents($attachment->getName(), $fileContent);
    }
    // 处理嵌套项附件(如内嵌邮件、日历项等)
    if ($attachment->getOdataType() === '#microsoft.graph.itemAttachment') {
        $embeddedItem = $attachment->getItem();
        // 编写嵌套项的对应处理逻辑
    }
}
  1. 如果你使用的SDK版本没有封装getContentBytes()方法,可以调用模型基类的公共方法getProperties()获取全量属性数组后读取对应字段:
$props = $attachment->getProperties();
if (isset($props['contentBytes'])) {
    $contentBytes = $props['contentBytes'];
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 12:39:23