【问题标题】:Python Graph API request only retrieving 1 attachment from an emailPython Graph API 请求仅从电子邮件中检索 1 个附件
【发布时间】:2021-05-12 15:57:17
【问题描述】:

我正在使用 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 项。

【问题讨论】:

  • 对我来说看起来很奇怪,无论您使用什么客户端,如果调用是完美的,那么您获得的数据在所有情况下都是相同的。试试这样的/attachments?$top=20 看看它是否有效。
  • 试试 Shiva 上面的建议。但我怀疑上面的东西。 7 个是实际附件,我认为 3 个是内联附件。如果是这种情况,上面的 Graph API 调用将不起作用。
  • 另外,你可以尝试做附件列表(一层嵌套,但不能保证内联附件) GET /users/{id | userPrincipalName}/mailFolders/{id}/childFolders/{id}/messages/{id}/attachments/{id}

标签: python microsoft-graph-api postman


【解决方案1】:

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

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 2017-03-07
    • 2012-01-12
    • 1970-01-01
    • 2019-05-05
    相关资源
    最近更新 更多