if (attachment instanceof FileAttachment) { FileAttachment fileAttachment = (FileAttachment) attachment; byte[] content = fileAttachment.getContentBytes(); // Save to local file java.nio.file.Files.write(java.nio.file.Paths.get(attachment.getName()), content); } Use code with caution.
First, retrieve the metadata for all attachments on a specific message. You’ll need the messageId of the email you are targeting. microsoft graph api download email attachment java
// Using Client Credentials Flow (App-only access) ClientSecretCredential credential = new ClientSecretCredentialBuilder() .clientId("YOUR_CLIENT_ID") .clientSecret("YOUR_CLIENT_SECRET") .tenantId("YOUR_TENANT_ID") .build(); GraphServiceClient graphClient = new GraphServiceClient(credential, "https://microsoft.com"); Use code with caution. Step 2: List Message Attachments The SDK uses an AuthenticationProvider to handle token
AttachmentCollectionResponse attachments = graphClient.users("user@example.com") .messages("MESSAGE_ID") .attachments() .get(); for (Attachment attachment : attachments.getValue()) { System.out.println("Found attachment: " + attachment.getName()); } Use code with caution. Step 3: Download the Attachment Content There are two primary ways to get the actual file data: Option A: Direct Byte Array (For Files < 3MB) you must first authenticate.
To interact with the API, you must first authenticate. The SDK uses an AuthenticationProvider to handle token acquisition.
For larger files or more efficient handling, you can call the /$value endpoint to get a raw InputStream . This avoids loading the entire byte array into memory.
Option B: Using the /$value Endpoint (Recommended for Streams)