Attach PDF to e-mail

9.5k views Asked by At

What I want to do is attach one or several PDFs to an e-mail. I am currently using MimeMessage to send emails which works flawlessly. The problem however is that I have no idea how to attach files. (More specifically PDFs I create using itext).

Any examples or tips are appreciated!

3

There are 3 answers

2
Maxym On BEST ANSWER

This reading ("How to create an in-memory PDF report and send as an email attachment using iText and Java") should help you

0
Geoffrey De Smet On

Create an attachment on the MimeMessage (see javadocs), set the content type to "application/pdf", get the content OutputStream of it and write the bytes of the PDF to it (with Apache's commons-io IOUtils).

1
Impiastro On

You can use the famous Apache Jakart library called Commons Email.

If your emails are in html format you can use this code:

HtmlEmail email = new HtmlEmail();
email.setSubject("<your subject>");
email.setHtmlMsg("<your html message body>");
email.setHostName("<host>");
email.setFrom("<from_address>");
email.addTo("<recipient_address>");
email.send();

and then attach your pdf files

EmailAttachment attachment = new EmailAttachment();

String filePath = "pathtofile";
attachment.setPath(filePath);
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("description for this attachment");

email.attach(attachment);

Otherwise you should use the MultiPartEmail class.

Hope can be helpful...

ROb