3

I am trying to read an email attachment using Microsoft Graph API(v2) but I am getting "Object reference not set to an instance" error

I have verified the app permissions in Azure Active Directory and has all the permissions set mentioned in microsoft documentation

Mail.Read Group.Read.All (Added extra permission to try) I am able to read the message and its content correctly and even the message "HasAttachments" property is true but when I call API again to fetch attachments it gives error.

Also tried to create new token for fetching attachments considering the fact that existing one would have expired but no luck

OutlookServicesClient client = new OutlookServicesClient(new Uri(OutlookAPI), GetAccessToken);

client.Context.SendingRequest2 +=
                    new EventHandler<Microsoft.OData.Client.SendingRequest2EventArgs>((sender, e) => InsertXAnchorMailboxHeader(sender, e, userEmail));
 var attachments = await client.Me.MailFolders.GetById(constInbox).Messages.GetById(strMessageID).Attachments.ExecuteAsync();


public async Task<string> GetAccessToken()
        {
       string accessToken = null;
           using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(TokenUri);
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
                var requestContent = string.Format("grant_type=password" + "&client_id=" + appId +
                                                    "&client_secret=" + appPassword +
                                                    "&resource=" + Resource +
                                                    "&username=" + userEmail +
                                                   "&password=" + passwd);
                var content = new StringContent(requestContent, Encoding.UTF8, "application/x-www-form-urlencoded");
                var response = client.PostAsync(client.BaseAddress, content).Result;
                var result = response.Content.ReadAsStringAsync().Result;
                var jobject = JsonConvert.DeserializeObject<JObject>(result);
                accessToken = jobject.GetValue("access_token").ToString();
            }
            return accessToken;
        }

Attaching Quickwatch for client.Kindly check client on runtime

Dipti K
  • 31
  • 2
  • The error says that some object is not set. Have you properly initialized `client1`? Please show a bit more of your code. – LocEngineer Sep 09 '19 at 09:58
  • Following is the code I am using for initializing client: OutlookServicesClient client1 = new OutlookServicesClient(new Uri(OutlookAPI), GetAccessToken); client.Context.SendingRequest2 += new EventHandler((sender, e) => InsertXAnchorMailboxHeader(sender, e, userEmail)); – Dipti K Sep 10 '19 at 07:50
  • GetAccessToken() has following logic: client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var requestContent = string.Format("grant_type=password" + "&client_id=" + appId + "&client_secret=" + appPassword + "&resource=" + Resource + "&username=" + userEmail + "&password=" + passwd); – Dipti K Sep 10 '19 at 07:51
  • Do I have to set any specific settings for reading attachments? – Dipti K Sep 10 '19 at 07:52
  • Please edit your post to include the additional code. It is rather difficult to read code in a comment and it lacks context if not shown in relation to the rest of the code. have you checked whether you get a proper Access Token? Have you set breakpoints and *verified* that client is correctly initialized? – LocEngineer Sep 10 '19 at 07:57
  • Please check the edited post.I am getting access token correctly.Is there anything specific I have to check in client? – Dipti K Sep 10 '19 at 08:53
  • Ah yes. You initialize `client` **after** you call `await client.` <= There's the rub! Move the first line to the third. – LocEngineer Sep 10 '19 at 08:59
  • Please check I am able to initialize client properly and also I am able to read mails appropriately.Let me know if you need any specific value – Dipti K Sep 10 '19 at 11:59
  • Not experienced in Graph API but according to documentation, your call `.Attachments.ExecuteAsync()` should rather be `.Attachments.Request().GetAsync();`. https://learn.microsoft.com/en-us/graph/api/attachment-get?view=graph-rest-1.0&tabs=csharp – LocEngineer Sep 10 '19 at 12:08
  • Yes but it gives error when we write .Attachments.Request().GetAsync();....Error CS1061 'IAttachmentCollection' does not contain a definition for 'Request' and no accessible extension method 'Request' – Dipti K Sep 10 '19 at 12:18
  • You're still doing something wrong. It should work according to the documentation: https://learn.microsoft.com/en-us/graph/api/message-list-attachments?view=graph-rest-1.0&tabs=csharp Please update your code to reflect your current status. – LocEngineer Sep 10 '19 at 12:28
  • I was encountering the same behavior working with the `GraphServiceClient`. I needed to perform another request to get the attachments after the first query that got the message(s). This [question](https://stackoverflow.com/questions/49147472/microsoft-graph-saving-file-attachments-through-c) Specifically Tomáš Paul's answer helped me and may be what you need for the `OutlookServicesClient` – Brandon McClure Apr 03 '20 at 19:26

0 Answers0