Tommy
Tommy

Reputation: 4111

How to attach a file to an email using JavaMail

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);

Upvotes: 4

Views: 5812

Answers (2)

Jacob Mattison
Jacob Mattison

Reputation: 51052

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).

Upvotes: 3

jheddings
jheddings

Reputation: 27553

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);

Upvotes: 7

Related Questions