JavaMail sending mail attachment from string - encoding UTF-8

Ibolit picture Ibolit · Feb 10, 2011 · Viewed 54.7k times · Source

My application has to send a textfile, which it first has to generate as a String. The text contains non-ASCII symbols, so i would like it to be UTF-8. I've tried a lot of variants, but all i receive as the attachment is some question marks. And, when i send the same text as the message body, it works all right.

Here is the line of code that generates the MimeBodyPart with the attachment:

String attachment = "Привет";
messageBodyPart.setContent(new String(attachment.getBytes("UTF-8"),
    "UTF-8"),"text/plain; charset=UTF-8");

I also tried using the string without any transformations, using just the bytes, now, as you see, i am trying to generate a string from the bytes...

What am i doing wrong? (And i do remember doing this in another project, which works, but i no longer have the access to its source code).

Thank you in advance. Timofey.

UPDATE

Having read your replies, and after some more unsuccessful experimenting i thought it best to publish the code of my mailing thing. I have the Mailer class, which does the mailing, and other classes can just call its static sendMessage() method to send a message. And it all runs on Google App Engine.

public static void sendMessage(String to, String subject, String msgBody,
            String attachment) throws AddressException, MessagingException {

    Properties props = new Properties();

    Session mailSession = Session.getDefaultInstance(props, null);
    Message msg = new MimeMessage(mailSession);
    String email = "bla-bla-bla"; // userService.getCurrentUser().getEmail();

    msg.setFrom(new InternetAddress(email));
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

    InternetAddress[] addresses = { new InternetAddress("bla-bla-bla") };

    msg.setReplyTo(addresses);
    msg.setSubject(subject);

    Calendar cal = Calendar.getInstance();

    String fileName = cal.get(Calendar.YEAR) + "_"
            + cal.get(Calendar.MONTH) + "_"
            + cal.get(Calendar.DAY_OF_MONTH) + "_"
            + cal.get(Calendar.HOUR_OF_DAY) + "_"
            + cal.get(Calendar.MINUTE) + "_" + cal.get(Calendar.SECOND)
            + "_" + cal.get(Calendar.MILLISECOND) + ".txt";

    // create the message part
    MimeBodyPart messageBodyPart = new MimeBodyPart();

    // fill message
    // Here we should have the msgBody.
    // Sending attachment contents for debugging only.
    messageBodyPart.setText(attachment + " - 4", "UTF-8", "plain");

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);

    MimeBodyPart att = new MimeBodyPart();
    att.setText(attachment, "UTF-8", "plain");
    att.addHeader("Content-Type", "text/plain; charset=UTF-8"); 

    att.setFileName(fileName);
    multipart.addBodyPart(att);

    // Put parts in message
    msg.setContent(multipart);

    Transport.send(msg);
}

And the line that calls this thing in another class is:

Mailer.sendMessage("[email protected]", "Test", "No body", "Привет, Я кусок текста");

And the raw source of the mail, strangely enough, is (leaving out the seemingly irrelevant headers):

Message-ID: <[email protected]>
Date: Sat, 12 Feb 2011 11:21:01 +0000
Subject: Pages
From: [email protected]
To: [email protected]
Content-Type: multipart/mixed; boundary=00163662e7107ccbd4049c1402fa

--00163662e7107ccbd4049c1402fa
Content-Type: text/plain; charset=KOI8-R; format=flowed; delsp=yes
Content-Transfer-Encoding: base64

8NLJ18XULCDxIMvV08/LINTFy9PUwSAtIDQNCg==
--00163662e7107ccbd4049c1402fa
Content-Type: text/plain; charset=US-ASCII; name="2011_1_12_11_21_1_691.txt"
Content-Disposition: attachment; filename="2011_1_12_11_21_1_691.txt"
Content-Transfer-Encoding: base64

Pz8/Pz8/LCA/ID8/Pz8/ID8/Pz8/Pw==
--00163662e7107ccbd4049c1402fa--

I just don't get it, why the charsets are different from what i am trying to set, and where they come from.

Answer

Ibolit picture Ibolit · Feb 12, 2011

Set the content type to application/octet-stream:

MimeBodyPart attachmentPart = new MimeBodyPart();

try {
  DataSource ds = new ByteArrayDataSource(attachment.getBytes("UTF-8"), "application/octet-stream");
  attachmentPart = new MimeBodyPart();
  attachmentPart.setDataHandler(new DataHandler(ds));
} 
catch (Exception e) {
  Logger.getLogger("Blina").log(Level.SEVERE, Misc.getStackTrace(e));
}

attachmentPart.setFileName(fileName);
multipart.addBodyPart(attachmentPart);

// Put parts in message
msg.setContent(multipart);