在commons email中添加附件作为流

use*_*745 6 java jakarta-mail apache-commons-email

我在我的网络应用程序中使用Apache Commons Email,它工作正常.

现在我需要通过附件发送文档,我遇到了一些问题.我需要从数据库中获取文件(作为BLOB)并将其添加为附件.看起来Commons Email不支持流附件,它只从路径中获取文件.

我需要知道这里的最佳做法是什么?

  1. 我是否还需要将文件保存在目录结构中,以便它可以与Commons Email?一起使用,或者,
  2. 有什么方法可以使用流式内容本身作为附件添加?

tim*_*ooo 21

使用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("jdoe@somewhere.org", "John Doe");
email.setFrom("me@apache.org", "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();
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,工作得很好。虽然我不知道文件描述的用途。我在收到的电子邮件中没有看到任何内容。 (2认同)