以Pdf附件的形式发送电子邮件作为流

Att*_*cus 10 java email jakarta-mail mime-types

我想发送一个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);
    }
Run Code Online (Sandbox Code Playgroud)

这是我用来构建MimeBodyPart附件的代码:

    if (arrayInputStream != null && arrayInputStream instanceof ByteArrayInputStream) {
        MimeBodyPart attachment = new MimeBodyPart(arrayInputStream);
        attachment.setHeader("Content-Type", "application/pdf");
        mimeMultipart.addBodyPart(attachment);
    }
Run Code Online (Sandbox Code Playgroud)

这段代码给了我这个错误:

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="
Run Code Online (Sandbox Code Playgroud)

Att*_*cus 21

我找到了这个线程中建议的解决方案.似乎有一个DataSource专门为此目的而创建的类.希望这个例子也能帮助别人.

    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);
    }
Run Code Online (Sandbox Code Playgroud)

  • 这将完全读取InputStream,并且字节数组完全存储在ByteArrayDataSource中。因此,大型附件的内存使用率会很高。正确的 ? (2认同)

mtr*_*aut 5

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

你的第二个例子应该正确.你可以考虑一下

  • 不要转换为InputStream并返回,这将产生不必要的副本
  • 添加处置(例如bp.setDisposition(Part.ATTACHMENT);)


归档时间:

查看次数:

29425 次

最近记录:

7 年,11 月 前