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);
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 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With