Как получить вложение почтового файла office 365 (например, изображения, текстового файла и т. Д. c), используя API-интерфейс Oauth Graph Service Client в java? - PullRequest
0 голосов
/ 01 апреля 2020

Вот как я получаю список объектов вложений, прикрепленных к сообщению:

IAttachmentCollectionRequest attachmentsPage = graphClient
    .users(emailServer.getEmailAddress())
    .mailFolders("Inbox")
    .messages(mail.id)
    .attachments()
    .buildRequest();

List<Attachment> attachmentsData = attachmentsPage.get().getCurrentPage();
List<AttachmentData> attachmentDataToStore = new java.util.ArrayList<AttachmentData>();

for(Attachment attachment : attachmentsData)
{
    attachmentData.setInputStream(
        new ByteArrayInputStream(
            attachment.getRawObject()
                .get("contentBytes")
                .getAsString()
                .getBytes()));
}

Теперь я считаю, что преобразование байтов содержимого во входной поток не происходит должным образом и в конечном итоге данные (image.png ) развращается. Есть предложения?

1 Ответ

0 голосов
/ 16 апреля 2020

Используйте класс FileAttachment, чтобы обработать все это для вас. К сожалению, SDK не обрабатывает это самым «чистым» способом - вы должны запросить вложение во второй раз.

public static void saveAttachments(String accessToken) {
    ensureGraphClient(accessToken);

    final String mailId = "message-id";

    // Get the list of attachments
    List<Attachment> attachments = graphClient
        .me()
        .messages(mailId)
        .attachments()
        .buildRequest()
        // Use select here to avoid getting the content in this first request
        .select("id,contentType,size")
        .get()
        .getCurrentPage();

    for(Attachment attachment : attachments) {
        // Attachment is a base type - need to re-get the attachment as a fileattachment
        if (attachment.oDataType.equals("#microsoft.graph.fileAttachment")) {

            // Use the client to generate the request URL
            String requestUrl = graphClient
                .me()
                .messages(mailId)
                .attachments(attachment.id)
                .buildRequest()
                .getRequestUrl()
                .toString();

            // Build a new file attachment request
            FileAttachmentRequestBuilder requestBuilder =
                new FileAttachmentRequestBuilder(requestUrl, graphClient, null);

            FileAttachment fileAttachment = requestBuilder.buildRequest().get();

            // Get the content directly from the FileAttachment
            byte[] content = fileAttachment.contentBytes;

            try (FileOutputStream stream = new FileOutputStream("C:\\Source\\test.png")) {
                stream.write(content);
            } catch (IOException exception) {
                // Handle it
            }
        }
    }
}
...