views:

202

answers:

2

I am using Javamail (javax.mail) to send mails. I successfully adjusted contents of my mail as utf-8. However I could not set subject line as a utf-8 encoded string.

I tried even

mail.setSubject(new String(subject.getBytes("utf-8"), "utf-8"));

on subject however it still sends as Cp1252. Example headers from mail are given below:

Any ideas?

example from mail headers

A: 

Solved.

mail.setSubject(MimeUtility.encodeText(subject, "utf-8", "B"));

solves it and sends utf-8 encoded mail subjects. \n/

Ahmet Alp Balkan
thanks for posting solution
org.life.java
+2  A: 

You should use setSubject(String subject, String charset) which is a convenient function for this purpose.

Session session=Session.getDefaultInstance(new Properties());
MimeMessage mimeMsg= new MimeMessage(session);
String subject="Herr Müller reist nach \u0141\u00f3d\u017a.";
mimeMsg.setSubject(subject,"utf-8");
System.out.println(subject);
System.out.println(mimeMsg.getHeader("Subject")[0]);

In MimeUtility it is said:

There are a set of methods to encode and decode MIME headers as per RFC 2047. Note that, in general, these methods are not needed when using methods such as setSubject and setRecipients; JavaMail will automatically encode and decode data when using these "higher level" methods. The methods below are only needed when maniuplating raw MIME headers using setHeader and getHeader methods.

From my point of view, Message.setSubject should be the entry point for this purpose.

The cp1252 in your subject encoding shows up, because it is your standard encoding on your platform.

Your posted example is the "result" of

mail.setSubject(MimeUtility.encodeText(subject, "cp1252", "Q"));`
Michael Konietzka
My MimeMessage has no setSubject(String, String) interestingly. Maybe I'm using an older version of Javamail. thanks anyway.
Ahmet Alp Balkan
That must be a very old javamail, because even [MimeMessage in Version 1.1][1] of the year 1999 has it. ;-)[1]: https://www.cs.auckland.ac.nz/references/java/javamail/javax/mail/internet/MimeMessage.html
Michael Konietzka