我想发送一个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="
答案 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部分。
你的第二个例子应该是正确的。你可以考虑