How do you force the encoding of a file attachment?

Dieter Wimberger

You can do following:

  1. 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 the ByteArrayDataSource class that is one of the distribution's examples.
  2. Create the array holding the encoded data (here mime base64):

    InputStream in=new FileInputStream(file);
    ByteArrayOutputStream bout=
        new ByteArrayOutputStream();
    OutputStream out=
    int i=0;
    while((i=in.read())!=-1) {
        //maybe more efficient with a buffer
        //this is just demonstrative
  3. Set the name, type and the byte array (or pass it on construction).

    EncodedDataSource encds=
        new EncodedDataSource(contenttype,
          filename, bout.toByteArray());
  4. Add the header of the encoding and a the DataHandler to a MimeBodyPart(mbp):

    mbp.setDataHandler(new DataHandler(encds));

The above will work, yet, as far as I realized binary parts of mail sent are encoded anyway.