【问题标题】:How to download attachments using Microsoft Graph API?如何使用 Microsoft Graph API 下载附件?
【发布时间】:2019-02-27 16:22:42
【问题描述】:

我已经能够使用 Microsoft Graph API

获取邮箱和附件详细信息

示例请求

GET https://outlook.office.com/api/v2.0/me/messages/AAMkAGI2THVSAAA=/attachments?$select=Name

示例响应

状态码:200

{
    "@odata.context": "https://outlook.office.com/api/v2.0/$metadata#Me/Messages('AAMkAGI2THVSAAA%3D')/Attachments(Name)",
    "value": [
        {
            "@odata.type": "#Microsoft.OutlookServices.FileAttachment",
            "@odata.id": "https://outlook.office.com/api/v2.0/Users('ddfcd489-628b-40d7-b48b-57002df800e5@1717622f-1d94-4d0c-9d74-709fad664b77')/Messages('AAMkAGI2THVSAAA=')/Attachments('AAMkAGI2j4kShdM=')",
            "Id": "AAMkAGI2j4kShdM=",
            "Name": "minutes.docx"
        }
    ]
}

我需要使用 Microsoft Graph API 下载附件的服务。

【问题讨论】:

标签: rest office365 microsoft-graph-api


【解决方案1】:

供其他正在使用python的用户参考,希望可以帮助您节省一些时间

import io
import response

url = f"https://graph.microsoft.com/v1.0/me/messages/{email_id}/attachments/{attachment_id}/$value"

payload={}
headers = {
  'Content-Type': 'application/json',
  'SdkVersion': 'postman-graph/v1.0',
  'Authorization': f'Bearer {access_token}'
}

response = requests.request("GET", url, headers=headers, data=payload, allow_redirects=False)

toread = io.BytesIO()
toread.write(response.content)
toread.seek(0)

df = pd.read_excel(toread)
print(df)

【讨论】:

    【解决方案2】:

    使用 C#.NET 时:

    await graphClient.Users["coyote@acme.com"].MailFolders.Inbox.Messages.Request()
                    .Expand("attachments").GetAsync();
    

    await graphClient.Me.MailFolders.Inbox.Messages.Request()
                    .Expand("attachments").GetAsync();
    

    问候

    【讨论】:

      【解决方案3】:

      是的,您可以从 Microsoft Graph API 本地下载文件。您需要将字节流转换为 base64 解码数据。这是代码

      $curl = curl_init();
      curl_setopt_array($curl, array(
        CURLOPT_URL => "https://graph.microsoft.com/v1.0/me/messages/your_message_id/attachments",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => array(
          "Prefer: IdType=\"ImmutableId\"",
          "Authorization: Bearer your_access_token"
        ),
      ));
      
      $response = json_decode(curl_exec($curl),true);
      curl_close($curl);
      
      $fileName = $response['value'][0]['name'];
      $contents = base64_decode($response['value'][0]['contentBytes']);
      
      header("Content-type: ".$response['value'][0]['contentType']);
      header("Content-Disposition: attachment; filename=" . $fileName);
      print $contents;
      die;
      

      【讨论】:

        【解决方案4】:

        根据您的描述,我假设您想使用 MS Graph API 下载附件。

        根据我的测试,我们可以使用以下步骤下载附件。

        Step1,我们应该使用以下 API 获取附件 ID:

        GET /me/messages/{id}/attachments

        GET /users/{id | userPrincipalName}/messages/{id}/attachments

        Step2,我们可以使用以下代码下载附件。

        Chilkat.StringBuilder sbSavePath = new Chilkat.StringBuilder();
        Debug.WriteLine("name: " + json.StringOf("value[i].name"));
        Debug.WriteLine("contentType: " + json.StringOf("value[i].contentType"));
        int sizeInBytes = json.IntOf("value[i].size");
        Debug.WriteLine("size: " + Convert.ToString(sizeInBytes));
        
        //  Extract the data and save to a file.
        sbSavePath.SetString("qa_output/");
        sbSavePath.Append(json.StringOf("value[i].name"));
        
        attachData.Clear();
        attachData.AppendEncoded(json.StringOf("value[i].contentBytes"),"base64");
        attachData.WriteFile(sbSavePath.GetAsString());
        
        //  Get the last-modified date/time and set the output file's last-mod date/time..
        lastMod.SetFromTimestamp(json.StringOf("value[i].lastModifiedDateTime"));
        fac.SetLastModified(sbSavePath.GetAsString(),lastMod);
        

        更详细的简单代码可以参考this document

        如果我们使用的是测试版的API,并且附件是在线文件,我们也可以使用sourceUrl属性来下载附件。

        这里是a closed issue about how to download attachment。可能对你有帮助。

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-16
        • 2017-07-01
        • 2020-04-11
        • 1970-01-01
        • 1970-01-01
        • 2023-02-04
        • 1970-01-01
        • 2022-01-06
        相关资源
        最近更新 更多