JAVAC
JAVAC

Reputation: 1270

java mail as pdf files as attachment

I am trying to send an e-mail with a PDF as an attachment. It was including the file but its size was less than what it was on disk, and when trying to open it, it says the file is corrupted.

MimeBodyPart messageBodyPart = new MimeBodyPart();
        Multipart multipart = new MimeMultipart();
        messageBodyPart = new MimeBodyPart();


        try {
            messageBodyPart.attachFile(new File(filePath+"/"+fileName), "application/pdf", null);

            String message = "file attached. ";            
            messageBodyPart.setContent(message, "text/html");
            multipart.addBodyPart(messageBodyPart);
            mail.setMultiBody(multipart);

Upvotes: 2

Views: 13970

Answers (2)

Bill Shannon
Bill Shannon

Reputation: 29971

You need two MimeBodyParts, one for the main message body and one for the attached file:

Multipart multipart = new MimeMultipart();
MimeBodyPart messageBodyPart = new MimeBodyPart();
String message = "file attached. ";
messageBodyPart.setText(message, "utf-8", "html");
multipart.addBodyPart(messageBodyPart);

MimeBodyPart attachmentBodyPart = new MimeBodyPart();
attachmentBodyPart.attachFile(new File(filePath+"/"+fileName), "application/pdf", null);
multipart.addBodyPart(attachmentBodyPart);
mail.setContent(multipart);

Upvotes: 3

Sadistik
Sadistik

Reputation: 135

Doing some research i found another topic about sending mail with pdf attachment here.

He does it by stream but i think that is what you need.

if (arrayInputStream != null && arrayInputStream instanceof ByteArrayInputStream) {
    // create the second message part with the attachment from a OutputStrean
    MimeBodyPart attachment= new MimeBodyPart();
    ByteArrayDataSource ds = new ByteArrayDataSource(arrayInputStream, "application/pdf"); 
    attachment.setDataHandler(new DataHandler(ds));
    attachment.setFileName("Report.pdf");
    mimeMultipart.addBodyPart(attachment);
}

You have to write your own implementation of javax.activation.DataSource to read the attachment data from an memory instead of using one of the included implementations (to read from a file, a URL, etc.). If you have the PDF report in a byte array, you can implement a DataSource which returns the byte array wrapped in a ByteArrayOutputStream. source

Upvotes: 5

Related Questions