Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 405
Tommy Avatar asked Dec 30 '22 11:12

Tommy


2 Answers

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);
like image 170
jheddings Avatar answered Jan 12 '23 14:01

jheddings


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

like image 44
Jacob Mattison Avatar answered Jan 12 '23 14:01

Jacob Mattison