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

时间:2011-01-27 13:44:57

标签: java email javamail 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);
    }

以下是我用来构建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="

2 个答案:

答案 0 :(得分:21)

我找到了this帖子中建议的解决方案。似乎只为此目的创建了一个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);
    }

答案 1 :(得分:5)

您使用的构造函数是解析来自传输的mime部分。

你的第二个例子应该是正确的。你可以考虑

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