Home > Software engineering >  Get attachments from Office365 email using Microsoft Graph
Get attachments from Office365 email using Microsoft Graph

Time:08-15

I am connecting to an Office365 mailbox in my organisation using the Graph API.

It connects fine, it returns the first 10 unread emails, the .HasAttachments if statement only runs when there is an attachment but item.Attachments or item.Atttachments.CurrentPage is erroring with 'Object reference not set to an instance of an object.'

My aim is to read unread emails, download/parse the attachment and then mark the email as read.

Can anyone advise where I'm going wrong?


// Auth code omitted for brevity...


var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

var messages = await graphClient.Users["[email protected]"].Messages
        .Request()
        .Filter("isRead eq false")
        .GetAsync();

    Console.WriteLine(messages.Count); // Returns "10".

    foreach (Microsoft.Graph.Message item in messages.CurrentPage)
    {
        Console.WriteLine(item.Sender.EmailAddress.Address); // Prints email address.
        if(item.HasAttachments == true)
        {
            Console.WriteLine("Has attachment"); // Prints when email has attachment.

            foreach (var attachment in item.Attachments.CurrentPage) // Errors
            {
                Console.WriteLine(attachment.Name);
            }
        }

    }```

CodePudding user response:

The default behavior is not to fetch attachment data. You have to ask for it and you have two options:

Option 1: You ask for it throught attachment id.

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var attachment = await graphClient.Me.Messages["{message-id}"].Attachments["{attachment-id}"]
    .Request()
    .GetAsync();

Option 2: You include a $expand on the Request Url.

GET https://graph.microsoft.com/v1.0/me/messages/AAMkADA1M-zAAA=/attachments/AAMkADA1M-CJKtzmnlcqVgqI=/?$expand=microsoft.graph.itemattachment/item

So you have to modify your actual implementation to something like this

var message = await graphClient.Users["[email protected]"].Messages[messageId]
    .Request()
    .Expand("attachments")
    .GetAsync();

Or this

var message = await graphClient.Users["[email protected]"].Messages
    .Request()
    .Expand("attachments")
    .GetAsync();

Documentation:

  • Related