7

I am using Apache Commons Email in my web-application and it works fine.

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.

I need to know what is the best practice here?

  1. Do I need to save the file in the directory structure also, so that it works fine with Commons Email?, or,
  2. Is there any way I can use the streamed content itself to add as an attachment?
skaffman
  • 398,947
  • 96
  • 818
  • 769
user644745
  • 5,673
  • 9
  • 54
  • 80

1 Answers1

22

Using MultiPartEmail#attach(DataSource ds, String name, String description) should work:

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();
dertkw
  • 7,798
  • 5
  • 37
  • 45
  • 2
    Thanks, worked fine. Although I have no idea what the file description is for. I didn't see anywhere in the received email. – Carcamano Aug 01 '12 at 16:52