playframeworkjakarta-mailoutputstreampdf-writer

Java Mail - Attach multiple pdf file and send mail


I want to attach multiple pdf files (According to the number of receipt, for example if 2 receipt is available, then two attachment should be created) and send a mail using javamail. I am able to attach single file and send an email, but When I am doing it for multiple attachment, there is no content inside the pdf attachment.

What I have tried:-

For pdf file creation:-

//rentReceiptId Will store receipt id of available receipt
String rentReceiptId[] = selectedCards.split(",");
int count = rentReceiptId.length;
byte[] bytes ={};
String filename[] = new String[count];
String byteArray[] = new String[count];


//For each receipt id create a pdf file
for(int i=0 ; i< rentReceiptId.length; i++) {

   ByteArrayOutputStream outputStream = null;
   try {
     outputStream = new ByteArrayOutputStream();
     outputStream.close();
     Document document = new Document();
     PdfWriter.getInstance(document, outputStream);
     document.open();
     document.addTitle("Rent Receipt PDF");
     document.addSubject("Testing email PDF");
     HTMLWorker htmlWorker=new HTMLWorker(document);
     String str = "<html><head></head><body>"+ "Contents that to be sent" +"</body></html>";
     htmlWorker.parse(new StringReader(str));
     document.addKeywords("iText, email");
     document.addAuthor("Test");
     document.addCreator("Test");
     document.close();
     bytes = outputStream.toByteArray();
     filename[i] = "RentReceipt-"+i+".pdf";
     String temp = new String(bytes);
     byteArray[i] = temp;

 }catch(Exception ex) {
                        ex.printStackTrace();
                    }


CompletableFuture.runAsync( () -> {
                    Thread.currentThread().setContextClassLoader( getClass().getClassLoader() );

                        EmailUtils.sendEmailMultipleAttachment(mailerClient,recipientId, "Email Rent Receipt  Attachment","Please follow below attachment",recipientName,filename,byteArray);

                    }, Executors.newSingleThreadExecutor()).exceptionally(exc ->  {
                exc.printStackTrace();
                return null;});

}

EmailUtils.java:-

public class EmailUtils {
public static void sendEmailMultipleAttachment(MailerClient mailerClient,String recEmail, String subject, String content, String userName,String[] filename, String[] multiObject){
        Email email = new Email()
                    .setSubject(subject)
                    .setFrom("Test <info@Test.com>")
                    .addTo(userName + " <" + recEmail + ">")
                    .setBodyHtml("html Content");

for(int i=0; i< filename.length ; i++) {
                     byte[] fileContents = 
  multiObject[i].getBytes(Charset.forName("UTF-8"));


  //Not Working
  email.addAttachment(fileName[i], fileContents ,"application/pdf");

}

 try{

                mailerClient.send(email);
            }
            catch (Exception ex)
            {
                ex.printStackTrace();
            }


Multiple file is being attached but there is no content within those file. When i tried for Single file, it works, Where i am going wrong?


Solution

  • Change

     String temp = new String(bytes);
     byteArray[i] = temp;
     bytes = outputStream.toByteArray();
    

    to

     bytes = outputStream.toByteArray();
     String temp = new String(bytes);
     byteArray[i] = temp;
    

    BTW, naming a String array "byteArray" is not a great choice. :-)

    It would also be much better to just pass an array of byte arrays, then use JavaMail's ByteArrayDataSource to add the attachment, but I don't know if your Email class can handle that.

    Converting the byte array to a String and then back to a byte array risks corrupting the content.