如何使用outputstream在java中添加附件到电子邮件 [英] How to add Attachments to Email in java using outputstream

查看:942
本文介绍了如何使用outputstream在java中添加附件到电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了javax.mail库的代码,你可以在其中添加附件到电子邮件:

I've seen the code for javax.mail library where you add attachments to the email doing this:

MimeBodyPart attachmentPart = new MimeBodyPart();
FileDataSource fds = new FileDataSource("C:/text.txt");
attachmentPart.setDataHandler(new DataHandler(fds));
attachmentPart.setFileName("text.txt");
multipart.addBodyPart(attachmentPart);

但这要求文件驻留在此磁盘上的某个位置。我想直接从电子邮件库中获取一个输出流,并直接从我写入该输出流的另一个地方将文件内容流入其中。这可能吗?

But this requires that the file reside somewhere on this disk. I would like to grab an outputstream right from the email library and stream file contents into it directly from another place where I write to that outputstream. Is this possible?

推荐答案

尝试使用ByteArrayDataSource,就像这样

Try using ByteArrayDataSource, like this

ByteArrayOutputStream baos = //Read the output stream
DataSource aAttachment = new  ByteArrayDataSource(baos.toByteArray(),"application/octet-stream");
MimeBodyPart attachmentPart = new MimeBodyPart();

attachmentPart.setDataHandler(new DataHandler(aAttachment));

这篇关于如何使用outputstream在java中添加附件到电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆