首页 > 解决方案 > Python Graph API 请求仅从电子邮件中检索 1 个附件

问题描述

我正在使用 python 脚本发送 API 请求以获取电子邮件的附件。我使用的电子邮件有 4 个附件(加上电子邮件签名中的图片)。python 请求仅检索 1 个附件以及签名中的图片。当使用具有完全相同信息的 Postman 时,它会检索所有附件以及图片。

关于如何获得其他附件的任何想法?

import requests
url = 'https://graph.microsoft.com/v1.0/users/{{users email}}/messages/{{messageID}}/attachments'
body = None
head = {"Content-Type": "application/json;charset=UFT-8", "Authorization": "Bearer " + accessToken}
response1 = requests.get(url, data=body, headers=head)
response = response1.text

下面显示了来自 python 脚本的响应,只有 7 个项目,而 Postman 响应有 10 个项目。

来自 python 脚本的响应 邮递员的回应

标签: pythonmicrosoft-graph-apipostman

解决方案


下面的代码检索多个附件(文件是附件名称的数组)

def execute(accessToken, messageID, files, noAttachments): 
    import os
    from os import path
    import requests
    import base64
    import json
    
    if noAttachments == "False":
        url = 'https://graph.microsoft.com/v1.0/users/{{users email}}/messages/{{messageID}}/attachments'
        body = {}
        head = {"Authorization": "Bearer " + accessToken}
        responseCode = requests.request("GET", url, headers=head, data = body)
        response = responseCode.text
        test = json.loads(responseCode.text.encode('utf8'))
        x, contentBytes = response.split('"contentBytes":"',1)
        if len(files) == 1:
            imgdata = base64.b64decode(str(contentBytes))  
            filename = "C:/Temp/SAPCareAttachments/" + files[0]
            with open(filename, 'wb') as f:
                f.write(imgdata)
        else:
            for file in test["value"]:
                imgdata = base64.b64decode(file["contentBytes"])
                if file["name"] in files:   
                    filename = "C:/Temp/" + file["name"]
                    with open(filename, 'wb') as f:
                        f.write(imgdata)
print(responseCode)

推荐阅读