'How to add attachment using Java in Microsoft Graph API
I've worked though most of the examples on Stack, but I'm still having an issue being able to add an attachment to the MS Graph API using Java. Some of the examples posted use methods that are no longer being used.
Here's the code inside the create message method:
FileAttachment fileAttachment = new FileAttachment();
fileAttachment.name = "Example text file";
Path path = Paths.get("/Users/user/Desktop/Text.txt");
fileAttachment.contentBytes = Files.readAllBytes(path);
. . .
graphClient.me()
.sendMail(UserSendMailParameterSet
.newBuilder()
.withMessage(message)
.withSaveToSentItems(saveToSentItems)
.build())
.buildRequest()
.post();
But, I can't find a method to add this attachment to the message.
I'm brand new at the MS Graph API, but have spent some hours on this already so I'm thankful for any suggestions.
Solution 1:[1]
Attachment can be added to a message.attachments
Example:
FileAttachment fileAttachment = new FileAttachment();
fileAttachment.name = "Example text file";
Path path = Paths.get("/Users/user/Desktop/Text.txt");
fileAttachment.contentBytes = Files.readAllBytes(path);
LinkedList<Attachment> attachmentsList = new LinkedList<Attachment>();
attachmentsList.add(fileAttachment);
AttachmentCollectionResponse attachmentCollectionResponse = new AttachmentCollectionResponse();
attachmentCollectionResponse.value = attachmentsList;
AttachmentCollectionPage attachmentCollectionPage = new AttachmentCollectionPage(attachmentCollectionResponse, null);
// add to your message
message.attachments = attachmentCollectionPage;
Resources:
Solution 2:[2]
Got it working!!! ...Check this URL below for the solution:
[MS Documentation Error Solution: ] https://docs.microsoft.com/en-us/answers/questions/527635/graph-api-attachment-add-not-working.html
Per the link above, the MS example code referenced was missing the line of code that makes sending the attachment work, at least for me.
fileAttachment.oDataType = "#microsoft.graph.fileAttachment";
Thanks to all!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user2250152 |
| Solution 2 | Morkus |
