Microsoft.Graph NuGet ItemAttachment contents

Jonathan Nordell 20 Reputation points
2023-03-16T20:36:00.88+00:00

Up until my last update of the Microsoft.Graph NuGet 5.2 package I was able to obtain the contents of message attachments of type ItemAttachment (i.e. emails attached to an email). It wasn't the most elegant method, but it worked.

        public async Task<string?> GetMessageAttachment(string upn, string msgId, string attId)
        {
            // create request url
            var requestUrl = graphClient.Users[upn].Messages[msgId].Attachments[attId].ToGetRequestInformationAppendSegmentToRequestUrl("$value");
            // create request
            var hrm = new HttpRequestMessage(HttpMethod.Get, requestUrl);
            // authenticate request
            await graphClient.AuthenticationProvider.AuthenticateRequestAsync(hrm);
            try
            {
                // send request and read response
                var response = await graphClient.HttpProvider.SendAsync(hrm);
                // read content
                var content = await response.Content.ReadAsStringAsync();
                return content;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

The latest version of the SDK has removed the properties and methods that made this possible. FileAttachment types still work perfectly, but I can't obtain the raw contents of an ItemAttachment any longer. Does anyone have a solution for this? I've spent way too much time searching the internet and forums for the solution and none of them cover the latest SDK package.

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,449 questions
0 comments No comments
{count} votes

Accepted answer
  1. Glen Scales 4,431 Reputation points
    2023-03-17T01:12:03.92+00:00

    You can modify the urlTemplate as another workaround eg the following for me works on 5.2

                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");
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful