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

如何解码MS Graph API返回的zip附件contentBytes并提取内部txt文件内容

错误原因

复用代码抛出解码错误的核心原因是:.zip是二进制压缩格式,base64解码后得到的是压缩包二进制数据,不是纯文本内容,不能直接用utf-8编码解码。

解决方案

不需要本地存储文件,直接用Python内置的io.BytesIO将解码后的二进制字节流包装成内存类文件对象,再通过zipfile模块读取压缩包内的.txt内容即可,完全不需要依赖实体文件。

完整可运行代码

import base64
import io
import json
import zipfile
import requests

def getAttachmentFromMailMessage(mailId, headers):
    url = inboxFolderPricingFiles + '/' + mailId + '/' + 'attachments'
    response = requests.request('GET', url, headers=headers)
    attachment = json.loads(response.text)['value'][0]
    content_bytes = base64.b64decode(attachment['contentBytes'])
    
    # 同时适配zip和纯txt两种附件场景
    if attachment['name'].endswith('.zip'):
        # 内存中处理zip文件,无需落地到磁盘
        with zipfile.ZipFile(io.BytesIO(content_bytes)) as zip_obj:
            # 取压缩包内第一个文件,适配你当前压缩包仅存1个txt的场景
            txt_file = zip_obj.namelist()[0]
            txt_string = zip_obj.read(txt_file).decode('utf-8')
    else:
        txt_string = content_bytes.decode('utf-8')
    
    return txt_string

验证结果

使用你提供的zip附件contentBytes测试,返回值与独立txt附件解析结果完全一致:

this is some test text

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 06:15:03