以Pdf附件forms发送电子邮件作为流
我想发送一个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); )
我找到了这个post中建议的解决方案。 似乎只为此目的创建了一个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); }