我想附加多个pdf文件(根据收据的数量,例如如果有2个收据,那么应该创建两个附件)并使用javamail发送邮件。我可以附加单个文件并发送电子邮件,但是当我为多个附件执行此操作时,pdf 附件中没有内容。
我尝试过的:-
对于 pdf 文件创建:-
//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();
}
正在附加多个文件,但这些文件中没有内容。当我尝试单个文件时,它可以工作,我哪里出错了?