Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download attachments using Microsoft Graph API?

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.

like image 606
mvm Avatar asked Oct 29 '22 04:10

mvm


2 Answers

When using C#.NET:

await graphClient.Users["[email protected]"].MailFolders.Inbox.Messages.Request()
                .Expand("attachments").GetAsync();

or

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

Regards

like image 73
Martin.Martinsson Avatar answered Nov 15 '22 11:11

Martin.Martinsson


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;
like image 44
Rishabh Rawat Avatar answered Nov 15 '22 12:11

Rishabh Rawat