Javamail changing charset of subject line

…衆ロ難τιáo~ 提交于 2020-01-01 04:30:10

问题


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 http://m.friendfeed-media.com/a328a80db12f3c17a8aed06be106045354355abf


回答1:


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"));`



回答2:


Solved.

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

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

the legal values for "encoding" are "Q" and "B"... The "Q" encoding is recommended for use when most of the characters to be encoded are in the ASCII character set; otherwise, the "B" encoding should be used.

See http://tools.ietf.org/html/rfc2047.




回答3:


Problem solved!

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

solves it and sends utf-8 encoded mail subjects.

Why there is that "B" why there isn't ISO-something?




回答4:


I ran into a similar problem with Apache Camel Mail, which uses Java Mail. Setting

exchange.setProperty(Exchange.CHARSET_NAME, "UTF-8");

before routing to SMTP, solved the problem.




回答5:


The MimeMessage.setSubject(String subject, String charset) method will solve the problem: mimeMsg.setSubject(subject,"utf-8");

This is an updated link. Previous documentation link was dismissed by Oracle after Oracle bought the Sun.



来源:https://stackoverflow.com/questions/3451256/javamail-changing-charset-of-subject-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!