2011-08-26 129 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

啊,太慢了。已經在 –