tags:

views:

199

answers:

2

I need to send a PDF file using JavaMail. The PDF is currently a byte[]. How do I get it into the DataSource?

byte[] pdffile = ....

messageBodyPart = new MimeBodyPart();

DataSource source = ???

messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);

multipart.addBodyPart(messageBodyPart);
+5  A: 

Use javax.mail.util.ByteArrayDataSource:

DataSource source = new ByteArrayDataSource(pdffile, "application/pdf");

As you probably know, if the PDF is on the filesystem, it would be easier to the FileDataSource:

DataSource source = new FileDataSource(pdfpath);
jheddings
Excellent! For some reason I didn't have the javax.mail.util package, had to download it
Tommy
+3  A: 

jheddings answer seems correct to me, but I'll also add that if, by any chance, you are using Spring framework in your application, you could take advantage of the Spring MimeMessageHelper, which includes a nice addAttachment() method (and makes the rest of the message creation easier as well).

JacobM
CommonsEmail (http://commons.apache.org/email/) is also worth a shot. If you aren't using Spring already you'll have to bring in a few MB worth of jars just to get the email support, so commons might keep things simpler.
Jason Gritman
Good suggestion; I definitely wouldn't add Spring just for this purpose, but many folks are using it already.
JacobM