如何将Microsoft Graph获取的Attachment转换为byte[](Spring Boot)
解决Spring Boot中Microsoft Graph邮件附件转byte[]的问题
方案1:直接从FileAttachment获取字节数组
绝大多数普通附件都属于FileAttachment类型,直接强转后就能拿到内置的字节数组属性,这是最简便的方式:
Attachment attachment = _userClient.me().messages(listIdMessage.get(i)).attachments(idAttachment) .buildRequest() .get(); // 强转为FileAttachment类型 if (attachment instanceof FileAttachment fileAttachment) { byte[] fileBytes = fileAttachment.getContentBytes(); // 示例:将字节数组写入文件 try (OutputStream outputStream = new FileOutputStream("path/file/" + fileAttachment.getName())) { outputStream.write(fileBytes); } catch (IOException e) { e.printStackTrace(); } }
方案2:通过content()接口获取输入流转byte[]
如果需要处理特殊类型附件,或者必须通过流的方式获取内容,修正代码语法并手动将输入流转为字节数组:
try { // 获取附件内容输入流 InputStream inputStream = _userClient.me().messages(listIdMessage.get(i)).attachments(idAttachment) .content() .buildRequest() .get(); // 将InputStream转换为byte[] byte[] fileBytes; try (ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream()) { byte[] buffer = new byte[1024]; int readLength; while ((readLength = inputStream.read(buffer)) != -1) { byteOutStream.write(buffer, 0, readLength); } fileBytes = byteOutStream.toByteArray(); } finally { inputStream.close(); } // 示例:写入文件 try (OutputStream fileOutStream = new FileOutputStream("path/file/" + attachment.getName())) { fileOutStream.write(fileBytes); } } catch (Exception e) { e.printStackTrace(); }
你原来代码的问题说明
- 存在语法错误:
byte[] fileBytes = attachment.additionalDataManager().这行代码未完成,直接导致编译失败 - 调用
content()时如果报错,大概率是权限配置问题,需确保你的Microsoft Graph应用已申请Mail.Read权限
内容的提问来源于stack exchange,提问作者Juan Moreno
相关产品推荐
相关产品推荐

