我想将Pdf作为电子邮件附件发送(我正在使用JavaMail API)。我将Pdf(由jasper生成)作为byte[]

public InputStream exportPdfToInputStream(User user) throws ParseErrorException, MethodInvocationException, ResourceNotFoundException, JRException, IOException{
        JasperPrint jasperPrint = createJasperPrintObject(user);
        byte[] pdfByteArray = JasperExportManager.exportReportToPdf(jasperPrint);
        return new ByteArrayInputStream(pdfByteArray);
    }

这是我用来构造将作为附件的MimeBodyPart的代码:
    if (arrayInputStream != null && arrayInputStream instanceof ByteArrayInputStream) {
        MimeBodyPart attachment = new MimeBodyPart(arrayInputStream);
        attachment.setHeader("Content-Type", "application/pdf");
        mimeMultipart.addBodyPart(attachment);
    }

这段代码给了我这个错误:
javax.mail.MessagingException: IOException while sending message;
  nested exception is:
    java.io.IOException: Error in encoded stream: needed at least 2 valid base64 characters, but only got 1 before padding character (=), the 10 most recent characters were: "\24\163\193\n\185\194\216#\208="

最佳答案

您使用的构造函数用于解析传输中的mime部分。

您的第二个示例应该可以正确解决。你可能会考虑

  • 不会转换为InputStream并返回,这会使
  • 成为不必要的副本
  • 添加处置(例如 bp.setDisposition(Part.ATTACHMENT); )
  • 09-08 08:04