AloNE
AloNE

Reputation: 311

How to attach Pdf file to mail

I am try to attach a ready pdf file to mail using java,so for that I have try below

String filename = "file.pdf";

 ByteArrayOutputStream bos = new ByteArrayOutputStream();
??.write(bos);

 DataSource fds = new ByteArrayDataSource(bos.toByteArray(), "application/pdf");
 MimeBodyPart mbp2 = new MimeBodyPart();            
 mbp2.setDataHandler(new DataHandler(fds));   
 mbp2.setFileName(filename); 

I am ot understand what will be instead of '??'. so please suggest me about that.

Upvotes: 1

Views: 5954

Answers (2)

Jay Gajjar
Jay Gajjar

Reputation: 2741

javax.mail.util.ByteArrayDataSource introduced in JavaMail 1.4 and following are some pointers on same

If you use Spring's JavaMail API, you can do this sort of thing fairly easily (or at least, as easily as the JavaMail API allows, which isn't much).

The attachment data can be any of Spring's Resource abstractions, ByteArrayResource is just one of them.

Note that this part of the Spring API stands on its own, it does not require (but does benefit from) the Spring container.

JavaMailSenderImpl mailSender = ... instantiate and configure JavaMailSenderImpl here
final byte[] data = .... this holds my PDF data

mailSender.send(new MimeMessagePreparator() {
   public void prepare(MimeMessage mimeMessage) throws Exception {
      MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);
     // set from, to, subject using helper
     helper.addAttachment("my.pdf", new ByteArrayResource(data));
   } 
});

Upvotes: 2

Shuhail Kadavath
Shuhail Kadavath

Reputation: 448

Please refer the below code :

 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);
}

Upvotes: 0

Related Questions