1

I have a PDF Files Encoded with Base64, now I want to send the PDF's and allow to open from mail.

I was reading this question, But IS not working for me https://stackoverflow.com/a/9124625/811293

  Message message = new MimeMessage(session);
  message.setFrom(new InternetAddress(from));
  message.setSentDate(new Date());
  message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sendTo));
  message.setSubject("Subject - " + new Date());
  Multipart multipart = new MimeMultipart();

  MimeBodyPart mimeBodyPart = new MimeBodyPart();
  mimeBodyPart.setContent("contentMessage", "text/html");  // YES FOR NOW SIMPLE MESSAGE
  multipart.addBodyPart(mimeBodyPart);


  MimeBodyPart attachmentOnFly = new MimeBodyPart();

  /*
  //In the future the PDF will be created on Fly (Will not be stored)
  InputStream inputStream = new FileInputStream("/path/to/encoded/Base64/file.pdf");//new ByteArrayInputStream("Bytes from source".getBytes());
  ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(inputStream, "application/pdf");
  attachmentOnFly.setDataHandler(new DataHandler(byteArrayDataSource));
   */


  attachmentOnFly.attachFile(new File("/path/to/encoded/Base64/file.pdf"));
  attachmentOnFly.setHeader("Content-Type", "application/pdf");
  attachmentOnFly.setHeader("Content-Transfer-Encoding", "base64");
  attachmentOnFly.setDisposition(Part.ATTACHMENT);
  attachmentOnFly.setFileName("myFileName.pdf");
  multipart.addBodyPart(attachmentOnFly);

  message.setContent(multipart);
  Transport.send(message);

My problem, is when the mail isreceived, I can't open the PDF, But using Telnet alternative is working.

How Send Enconded Base64 PDF and that can be opened from the mail?

VGR
  • 40,506
  • 4
  • 48
  • 63
joseluisbz
  • 1,491
  • 1
  • 36
  • 58
  • Are you performing base64 encoding before attaching the PDF? I’m pretty sure you shouldn’t. – VGR Dec 04 '19 at 00:26
  • @VGR Yes, the File ins encode before attached, then how to proced? – joseluisbz Dec 04 '19 at 10:59
  • Try using the [PreencodedMimeBodyPart](https://docs.oracle.com/javaee/7/api/javax/mail/internet/PreencodedMimeBodyPart.html) class. It appears to be designed precisely for what you are trying to do. It extends MimeBodyPart, so it has all of the same methods. When using it, you won’t need to set the Content-Transfer-Encoding header; instead, you pass that value in the constructor. – VGR Dec 04 '19 at 12:37
  • Make sure that the PDF you are trying to send is actually properly formatted. Try opening the PDF from the original location on /path/to/encoded/Base64/file.pdf – dbrin Mar 11 '20 at 20:10

0 Answers0