2011-08-26 127 views

回答

6

主题是一个头。标题只使用ascii-7,所以要正确地编码没有ascii-7字符,你应该使用正确的编码。

如果您正在使用的类允许您使用UTF-8指示某些编码尝试。

mimeMessage.setSubject(yourSubject, "UTF-8"); 

如果你手写的标题使用任何的这个:

MimeUtility.encodeWord(yourSubject, "UTF-8", "B"); // base-64 
MimeUtility.encodeWord(yourSubject, "UTF-8", "Q"); // quoted-printable 

这或多或少什么的MimeMessage确实在SETSUBJECT(STR,编码):

setHeader("Subject", MimeUtility.fold(9, MimeUtility.encodeText(subject, charset, null))); 
// fold splits the value in several lines with no more than 72 chars 

样本

我试过这个:

public static void main(String[] args) throws Exception { 
      // manual encoding 
     System.out.println(MimeUtility.encodeText("How to include £ pound symbol", "UTF-8", "Q")); 
     System.out.println(MimeUtility.encodeText("How to include £ pound symbol", "UTF-8", "B")); 

      // MimeMessage encoding 
     MimeMessage m = new MimeMessage((Session) null); 
     m.setSubject("How to include £ pound symbol", "UTF-8"); 
     m.setContent("lalala", "text/plain"); 
     m.writeTo(System.out); 
    } 

输出功率为:

=?UTF-8?Q?How_to_include_=C2=A3_pound_symbol?= 
=?UTF-8?B?SG93IHRvIGluY2x1ZGUgwqMgcG91bmQgc3ltYm9s?= 

(...)

Message-ID: <[email protected]> 
Subject: =?UTF-8?Q?How_to_include_=C2=A3_pound_symbol?= 
MIME-Version: 1.0 
Content-Type: text/plain; charset=us-ascii 
Content-Transfer-Encoding: 7bit 

lalala 

反正你总是可以使用:

String yourEncodedString = MimeUtility.encodeText(str, "UTF-8", "Q"); 
mimeMessage.setHeader("Subject", yourEncodedString); 
+0

上发表评论之前,我已经尝试了谷歌之后的第一个片段,然后再问这个问题,并且不适合我。我不写头。 –

+1

尝试做'mimeMessage.writeTo(System.out);'所以我们可以看到如何编码你的主题(使用'setSubject(str,“UTF-8”)'提案)。我很好奇... – helios

+0

添加了我试过的样本 – helios

1

设置你的编码设置为UTF-8 ..

msg.setContent(message,"text/html; charset=UTF-8"); 
+2

这表明该MIME部分(主要内容)的主体的编码,但它不涉及到标题编码(主题在哪里)。我不确定Message的实现是否也使用这种编码来正确编码标题(特别是如果他们需要自己奇怪的编码) – helios

+1

这会影响主题行吗? –

+0

啊,太慢了。已经在 –