How to attach a file to an email using JavaMail

寵の児 提交于 2019-12-22 08:48:33

问题


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

回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/1744687/how-to-attach-a-file-to-an-email-using-javamail

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!