java 在公共电子邮件中添加附件作为流
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6806407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
add attachment as stream in commons email
提问by user644745
I am using Apache Commons Emailin my web-application and it works fine.
我在我的 web 应用程序中使用Apache Commons 电子邮件,它工作正常。
Now that I need to send a document by attachment, I am facing some problems. I need to get the file from the database (as a BLOB) and add it as an attachment. It seems like Commons Email does not support stream attachment and it only takes a file from a path.
现在我需要通过附件发送文档,我面临一些问题。我需要从数据库中获取文件(作为 BLOB)并将其添加为附件。似乎 Commons Email 不支持流附件,它只从路径中获取文件。
I need to know what is the best practice here?
我需要知道这里的最佳做法是什么?
- Do I need to save the file in the directory structure also, so that it works fine with Commons Email?, or,
- Is there any way I can use the streamed content itself to add as an attachment?
- 我是否还需要将文件保存在目录结构中,以便它与 Commons Email 一起工作?,或者,
- 有什么办法可以使用流式内容本身作为附件添加吗?
回答by dertkw
Using MultiPartEmail#attach(DataSource ds, String name, String description)should work:
使用MultiPartEmail#attach(DataSource ds, String name, String description)应该可以工作:
import org.apache.commons.mail.*;
// create the mail
MultiPartEmail email = new MultiPartEmail();
email.setHostName("mail.myserver.com");
email.addTo("[email protected]", "John Doe");
email.setFrom("[email protected]", "Me");
email.setSubject("The picture");
email.setMsg("Here is the picture you wanted");
// get your inputstream from your db
InputStream is = new BufferedInputStream(MyUtils.getBlob());
DataSource source = new ByteArrayDataSource(is, "application/pdf");
// add the attachment
email.attach(source, "somefile.pdf", "Description of some file");
// send the email
email.send();