2011-01-27 4 views
10

Desidero inviare un Pdf come allegato di posta elettronica (sto utilizzando l'API JavaMail). Ho il Pdf (generato da Jasper) come byte[].Invia e-mail in allegato Pdf come stream

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

Ecco il codice che sto usando per costruire la MimeBodyPart che sarà l'allegato:

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

Questo codice mi dà questo errore:

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=" 

risposta

5

Il costruttore è stato utilizzato sia per l'analisi una parte mimo dal trasporto.

Il tuo secondo esempio dovrebbe funzionare correttamente. Si può considerare

  • di non convertire in InputStream e ritorno, questo renderà le copie non necessarie
  • aggiungere una disposizione (ad esempio bp.setDisposition (Part.ATTACHMENT);)
+0

@mtraut: hai detto di non convertirlo in InputStream e tornare indietro, ma come posso farlo senza un InputStream? – Atticus

+1

utilizza il costruttore ** ByteArrayDataSource (byte [] data, tipo String) ** e il "pdfByteArray" – mtraut

+0

@mtraut: Grazie, è ciò che ho già inviato nella mia risposta. Ma grazie comunque. Anche se c'è un altro modo ancora più semplice per farlo! – Atticus

20

ho trovato un soluzione come suggerito nel thread this. Sembra che ci sia una classe DataSource creata proprio per questo scopo. Spero che questo esempio aiuti anche gli altri.

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); 
    } 
+0

usiamo questo gestore dati anche. – halil