java 将 pdf 文件作为附件发送

java mail as pdf files as attachment

我正在尝试发送带有 PDF 作为附件的电子邮件。它包括该文件,但它的大小小于它在磁盘上的大小,并且在尝试打开它时,它说文件已损坏。

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

经过一些研究,我发现了另一个关于发送带有 pdf 附件的邮件的主题 here

他是通过流来做的,但我认为这就是你需要的。

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

您需要 MimeBodyPart,一个用于正文,一个用于附件:

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