7

I've able to get mailbox and attachment detail using Microsoft Graph API

Sample request

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

Sample response

Status code: 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"
            }
        ]
    }

I need a service for download attachments using Microsoft Graph API.

t3chb0t
  • 16,340
  • 13
  • 78
  • 118
mvm
  • 193
  • 1
  • 4
  • 22
  • Answered here: https://stackoverflow.com/questions/34944174/how-to-retrieve-contents-of-an-itemattachment-via-the-microsoft-graph-api – felixmc Jan 16 '20 at 16:16

4 Answers4

8

When using C#.NET:

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

or

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

Regards

Martin.Martinsson
  • 1,894
  • 21
  • 25
5

Yes, you can download the file locally from Microsoft Graph API. You need to convert the byte stream to base64 decoded data. Here is the code

$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;
Rishabh Rawat
  • 1,083
  • 9
  • 15
3

for reference of other users that are using python, hope this will help you save some time

    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)
t3chb0t
  • 16,340
  • 13
  • 78
  • 118
chip
  • 3,039
  • 5
  • 35
  • 59
-1

According to your description, I assume you want to download the attachments using MS Graph API.

Based on my test, we can using the following steps to download the attachments.

Step1, we should get the attachments ID using the following APIs:

GET /me/messages/{id}/attachments

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

Step2, we can using the following code to download the attachment.

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);

For more detail about the simple code, we can refer to this document.

If we use the beta version of the APIs, and the attachment is a online file, we can also use the sourceUrl property to download the attachment.

Here is a closed issue about how to download attachment. It may be helpful for you.

Keen Jin
  • 1,060
  • 1
  • 6
  • 8
  • Is there any way to authenticate Microsoft Graph API using REST other than that loading URL GET https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F&response_type=code&scope=openid+Mail.Read – mvm Sep 24 '18 at 09:01
  • What did you mean? I have some misunderstand – Keen Jin Sep 24 '18 at 09:33
  • I have load auth URL in browser to get code value. Is there any way to authenticate using REST. https://login.microsoftonline.com/common/oauth2/v2.0/authorize? – mvm Sep 24 '18 at 09:53
  • We can request the url to authenticate using REST. For more detail, we can refer to [this document](https://developer.microsoft.com/en-us/graph/docs/concepts/auth_v2_user) – Keen Jin Sep 24 '18 at 13:47