一千萬個為什麽

搜索

以Pdf附件形式發送電子郵件作為流

我想發送一個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="

最佳答案

我找到了這個主題。似乎只為此目的創建了一個 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);
    }

轉載註明原文: 以Pdf附件形式發送電子郵件作為流