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

Answer

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



Source: stackoverflow