如何从字节数组构造文件以将文件作为附件发送到电子邮件中,而不将文件或文件路径保存到磁盘?

时间:2019-04-04 14:35:54

标签: java spring file spring-boot email

在Java中,我有一个字节数组,通常是来自外部API调用的文件。

我需要将此字节数组转换回文件,并将其作为附件发送到电子邮件 ,而无需创建实际文件或引用磁盘中的文件路径

我对进行外部API调用和构建带有文件附件的电子邮件感到很满意。除了我要创建的文件保存到磁盘然后作为附件通过电子邮件发送的事实。

尝试了使用FileOutputStream写入文件的常用方法。

//Convert Byte Array to File
byte[] byteArrayFileObj = someProcess();
File attachmentFile = new File("FileName.abc");
OutputStream os = new FileOutputStream(attachmentFile);
os.write(byteArrayFileObj);
os.close();

//Attach the File as an E-Mail Attachment
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.addAttachment(attachmentFile.getName(), attachmentFile);

我需要发送带有附件的文件的电子邮件,而无需将文件保存到磁盘。 就我而言,它将文件的副本保存到磁盘。

谷歌搜索很多。但是,这一点没有答案。预先谢谢。!

1 个答案:

答案 0 :(得分:0)

尝试一下:

final InputStreamSource fileStreamSource = new ByteArrayResource(byteArrayFileObj);
helper.addAttachment("Some-file-name", fileStreamSource);