Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring email add attachment

I am using Spring 3.2 and want to send an email with attachment. I have an array of bytes - how can I set it as an attachment? I am doing like this:

bytes[] doc = docDao.findNextDoc().getBytes();
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    helper.addAttachment("doc", ???); // how can I set bytes here?
}
.... 
// other things
like image 422
Bob Avatar asked May 08 '14 06:05

Bob


2 Answers

You can use addAttachment() with a DataSource or an InputStreamSource. Both interfaces offer Byte array implementations (e.g. ByteArrayDataSource or ByteArrayResource).

helper.addAttachment("doc", new ByteArrayResource(doc));

You also might reconsider polluting your memory with that byte array. Your DAO might support streams and so does addAttachment().

like image 50
Markus Malkusch Avatar answered Sep 29 '22 14:09

Markus Malkusch


You have ByteArrayResource:

import org.springframework.core.io.ByteArrayResource;
....
helper.addAttachment("doc", new ByteArrayResource(docDao.findNextDoc().getBytes());
like image 20
Danubian Sailor Avatar answered Sep 29 '22 16:09

Danubian Sailor