Search code examples
javamicrosoft-graph-api

How to add attachments(.txt, .pdf, .zip, etc) to email using graphapi in java code


I tried below code, for the first try I try to attach the .txt file.

private static void sendMailWithAttachment(String sFrom,String sSubject,String sContent,BodyType sContentType) {
        
         final Message message = new Message();
            message.subject = sSubject;
            message.body = new ItemBody();
            message.body.content = sContent;
            message.body.contentType = sContentType;
            
            LinkedList<Attachment> attachmentsList = new LinkedList<Attachment>();
            FileAttachment fileAttachment = new FileAttachment();
            
            fileAttachment.name = "Example text file";
           // Path path = Paths.get("/Users/user/Desktop/Text.txt");
                        
            fileAttachment.contentBytes = FileUtils.readAllBytes(path);
            
            fileAttachment.oDataType = "#microsoft.graph.fileAttachment";
            attachmentsList.add(fileAttachment);
            
            AttachmentCollectionResponse attachmentCollectionResponse = new AttachmentCollectionResponse();
            attachmentCollectionResponse.value = attachmentsList;
            AttachmentCollectionPage attachmentCollectionPage = new AttachmentCollectionPage(attachmentCollectionResponse, null);
            message.attachments = attachmentCollectionPage;
            
              _appClient.users("xxyy@xxyy.com")
                .sendMail(UserSendMailParameterSet
                    .newBuilder()
                    .withMessage(message)
                    .withSaveToSentItems(null)
                    .build())
                .buildRequest()
                .post();
    }

I am not understand that how to give the path which takes the attachment from the local system.


Solution

  • The path "/Users/user/Desktop/Text.txt" appears to be Windows Resource Management

    If the program and files are in different drive letters, you can use Paths.get("C:\\Users\\user\\Desktop\\Text.txt").

    If the program and file are in the same drive letter, you can use \\Users\\user\\Desktop\\Text.txt

    It is recommended to use java.io.File.separator as the directory separator to be compatible with different platforms