hudi
hudi

Reputation: 16525

How to save mail attachments in utf8

I need to save email attachment in utf8. I try this code but there is still some character missing:

public static void main(String args[]) throws Exception {
    File emlFile = new File("example.eml");

    InputStream source;

    source = new FileInputStream(emlFile);

    MimeMessage message = new MimeMessage(null, source);

    Multipart multipart = (Multipart) message.getContent();

    for (int x = 0; x < multipart.getCount(); x++) {

        BodyPart bodyPart = multipart.getBodyPart(x);
        String disposition = bodyPart.getDisposition();

        if (disposition != null && (disposition.equals(BodyPart.ATTACHMENT))) {
            System.out.println("Mail have some attachment : ");

            DataHandler handler = bodyPart.getDataHandler();
            System.out.println("file name : " + handler.getName());


            //start reading inpustream from attachment
            InputStream is = bodyPart.getInputStream();
            File f = new File(bodyPart.getFileName());
            OutputStreamWriter sout = new OutputStreamWriter(new FileOutputStream(f), "UTF8");
            BufferedWriter buff_out = new BufferedWriter(sout);
            int bytesRead;
            while ((bytesRead = is.read()) != -1) {
                buff_out.write(bytesRead);
            }
            buff_out.close();

        }
    }
}

Upvotes: 0

Views: 1416

Answers (1)

Joachim Isaksson
Joachim Isaksson

Reputation: 180927

You're reading bytes from the attachment ignoring any encoding, and outputting characters to the file. You'll most likely want to do either or and not mix the two.

If the attachment contains raw bytes, it makes no sense to UTF-encode the output and you can work with raw streams.

If it contains text, you'll want to also read the attachment as text instead of as raw bytes and use encoding for both reading and writing.

In the latter case something like;

InputStream is = bodyPart.getInputStream();
InputStreamReader sin = new InputStreamReader(is, 
                                              "UTF8"); // <-- attachment charset 

File f = new File(bodyPart.getFileName());
OutputStreamWriter sout = new OutputStreamWriter(new FileOutputStream(f), "UTF8");
BufferedReader buff_in = new BufferedReader(sin);
BufferedWriter buff_out = new BufferedWriter(sout);

int charRead;
while ((charRead = buff_in.read()) != -1) {
    buff_out.write(charRead);
}

buff_in.close();
buff_out.close();

Upvotes: 1

Related Questions