Send an E-Mail with attachment using JAVA Mail API without storing in local machine

后端 未结 3 1839
时光取名叫无心
时光取名叫无心 2020-12-06 17:29

I have report in my jsp page and I am writing that report in PDF Format. And I want to send the PDF as E-Mail with attachment, but I don\'t want store the file

相关标签:
3条回答
  • 2020-12-06 17:55

    You have to write your own implementation of javax.activation.DataSource to read the attachment data from an memory instead of using one of the included implementations (to read from a file, a URL, etc.). If you have the PDF report in a byte array, you can implement a DataSource which returns the byte array wrapped in a ByteArrayOutputStream.

    0 讨论(0)
  • 2020-12-06 17:57

    Since JavaMail 1.4 - mail.jar - contains javax.mail.util.ByteArrayDataSource

    • https://javamail.java.net/nonav/docs/api/javax/mail/util/ByteArrayDataSource.html
    • ( https://javamail.java.net/nonav/docs/api/ )
    • http://www.oracle.com/technetwork/java/javamail/index-138643.html - download location

    regards

    0 讨论(0)
  • 2020-12-06 18:02

    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). So you could write something like this:

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

    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.

    0 讨论(0)
提交回复
热议问题