Search code examples
microsoft-graph-apimicrosoft-graph-sdks

Save ItemAttachment as file Microsoft Graph API


We are moving from EWS to Graph API. In the EWS you could load the MimeContent for the ItemAttachment and save the MimeContent.Content to a file as an eml file. Can't find a way to do this for an ItemAttachment in Graph sdk. Have been able to get the ItemAttachment.Item as OutlookItem but don't know how to get the MimeContent or the OutlookItem as byte[]


Solution

  • You need to use the /$value path segment to do this see https://learn.microsoft.com/en-us/graph/api/attachment-get?view=graph-rest-1.0&tabs=http#get-the-raw-contents-of-a-file-or-item-attachment

    If your using the latest kiota based SDK then you need to use a workaround to do this as they don't currently support it directly eg

            var requestInformation = graphServiceClient.Me.Messages["AA..."].Attachments["AA..."].ToGetRequestInformation();
            requestInformation.UrlTemplate = requestInformation.UrlTemplate.Insert(requestInformation.UrlTemplate.Length, "/$value");           
            var attachmentStream = graphServiceClient.RequestAdapter.SendPrimitiveAsync<System.IO.Stream>(requestInformation).GetAwaiter().GetResult();
            using (var fileStream = File.Create("C:\\temp\\attachmentMessage.eml"))
            {
                attachmentStream.Seek(0, SeekOrigin.Begin);
                attachmentStream.CopyTo(fileStream);
            }
            Console.WriteLine("Done");