How do you force the encoding of a file attachment?
Created May 4, 2012
Dieter Wimberger You can do following:
- Write your own DataSource implementation that returns
type, name, and an InputStream that will read from an already encoded byte array (i.e.
a ByteArrayInputStream). See
javax.activation.DataSource
API for information about the DataSource interface, and theByteArrayDataSource
class that is one of the distribution's examples. - Create the array holding the encoded data (here mime base64):
InputStream in=new FileInputStream(file); ByteArrayOutputStream bout= new ByteArrayOutputStream(); OutputStream out= MimeUtility.encode(bout,"base64"); int i=0; while((i=in.read())!=-1) { //maybe more efficient with a buffer //this is just demonstrative out.write(i); } out.flush(); out.close();
- Set the name, type and the byte array
(or pass it on construction).
EncodedDataSource encds= new EncodedDataSource(contenttype, filename, bout.toByteArray());
- Add the header of the encoding and a the DataHandler to a MimeBodyPart(mbp):
mbp.addHeader("Content-Transfer-Encoding","base64"); mbp.setDataHandler(new DataHandler(encds));
The above will work, yet, as far as I realized binary parts of mail sent are encoded anyway.