-1

I have the below java program which send the pdf file as an attachment and that pdf file is read from my local system and then an mail is being generated in which that pdf file is being attached and then sent

below is the code now i have a query rite now as you can see in my code that file is read from my local system and ultimately being converted and stored in a byte array but when i going to send the mail it accepts the file name as a string so i was just trying to send the same file that is the encrypted on which is stored in a byte array please advise how can i send the same file that is the byte array itself

 //  attachment part
   MimeBodyPart attachPart = new MimeBodyPart();
  String filename = "c:\\index.pdf";

String filename_src = "c:\\index.pdf";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfReader reader = new PdfReader(filename_src);
PdfStamper stamper = new PdfStamper(reader, baos);
// Do the encrypting stuff
stamper.close();
byte[] result = baos.toByteArray(); //***** encrypted file in byte array ************


//*******program to send the encrypted file as an attachment ********
//accepts string as file name want to sore the above byte array itself 
   DataSource source = new FileDataSource(filename_dest);
    attachPart.setDataHandler(new DataHandler(source));
Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85
gfhtg hghg
  • 11
  • 1
  • 7

2 Answers2

0

Unless your Java mail library (semi-)automatically does (e.g. apache.commons.mail), you have to encode your attachment as Base64 payload and add a proper mime-type header before sending that payload via email.

You can refer to Apache Commons Email encode attach with base64 as example or following https://community.oracle.com/thread/1592976 you can add

 final String payload = Base64.Encoder.encodeToString(result);
 attachPart.setText(payload);
 attachPart.setHeader("Content-Type", "application/pdf"); // Use x-pdf instead for backward compatibility with old / legacy software
 attachPart.setHeader("Content-Transfer-Encoding", "base64");
Community
  • 1
  • 1
m c
  • 1,104
  • 1
  • 12
  • 21
0

See the ByteArrayDataSource class.

Bill Shannon
  • 29,579
  • 6
  • 38
  • 40