Search code examples
spring-bootparametersmicrosoft-graph-apiemail-attachmentsmicrosoft-graph-mail

How to get attachments from an email using the Microsoft Graph API?


I use the Spring Boot framework to develop a program that allows me to obtain the attached files of an email, but there is a code according to the Microsoft page that says that by means of the following code you can obtain the properties of the attached files, which is the following.

GraphServiceClient graphClient = GraphServiceClient.builder().authenticationProvider( authProvider ).buildClient();

Attachment attachment = graphClient.me().messages("AAMkADA1M-zAAA=").attachments("AAMkADA1M-CJKtzmnlcqVgqI=")
    .buildRequest()
    .get();

The doubt that I have is precisely what should be passed as parameter to the message() method, that according to this is passed "AAMkADA1M-zAAA=" according to an example that Microsoft Graph raises, but what is it? Is it the id of the tenant? or what is it?

In addition I also have doubt is in the parameter that happens in the attachments() method, really that AAMkADA1M-CJKtzmnlcqVgqI= What is it? What should be passed there?

I would like to know in those parameters what should be passed and how to obtain them to pass them?

What I expect from this code that Microsoft Graph proposes is to be able to obtain the attached files of an email, but according to that you must pass some parameters that I do not know and that I have already read on the web page and I have not found what those parameters that are passed in message() and attachments() refer to.


Solution

  • If you want to get attachments of a message you need to know the message id and the attachment id.

    • List messages
    MessageCollectionPage messages = graphClient.me().messages()
            .buildRequest()
            .select("id,sender,subject,hasAttachments")
            .get();
    
    • Select the message and use it's id to get list of attachments
    AttachmentCollectionPage attachments = graphClient.me().messages({message_id}).attachments()
        .buildRequest()
        .get();
    
    • Select the attachment
    Attachment attachment = graphClient.me().messages({message_id}).attachments({attachment_id})
        .buildRequest()
        .get();