2010-04-16 23 views
5

我在寫一段需要發送郵件給非ASCII名字的用戶的Java代碼。我已經想出瞭如何爲身體,主題行和通用標題使用UTF-8,但我仍然堅持在收件人將javax.mail.internet.MimeMessage發送給具有非ASCII名稱的收件人?

以下是我想要的「收件人:」字段中的內容:"ウィキペディアにようこそ" <[email protected]>。這生活(爲我們今天的目的)在一個叫recip字符串。

  • msg.addRecipients(MimeMessage.RecipientType.TO, recip)"忙俾ェ▎S]" <[email protected]>
  • msg.addHeader("To", MimeUtility.encodeText(recip, "utf-8", "B"))拋出AddressException: Local address contains control or whitespace in string ``=?utf-8?B?IuOCpuOCo+OCreODmuODh+OCo+OCouOBq+OCiOOBhuOBk+OBnSIgPA==?= =?utf-8?B?Zm9vQGV4YW1wbGUuY29tPg==?=''

如何赫克我應該送這條消息?


下面是如何處理的其他組件:

  • 身體HTML:msg.setText(body, "UTF-8", "html");
  • 頭:msg.addHeader(name, MimeUtility.encodeText(value, "utf-8", "B"));
  • 主題:msg.setSubject(subject, "utf-8");
+0

相關的問題和解決方案:http://stackoverflow.com/a/5650455/923560 – Abdull 2013-09-11 21:56:18

回答

5

唉,得到了它使用一個愚蠢的hack:

/** 
* Parses addresses and re-encodes them in a way that won't cause {@link MimeMessage} 
* to freak out. This appears to be the only robust way of sending mail to recipients 
* with non-ASCII names. 
* 
* @param addresses The usual comma-delimited list of email addresses. 
*/ 
InternetAddress[] unicodifyAddresses(String addresses) throws AddressException { 
    InternetAddress[] recips = InternetAddress.parse(addresses, false); 
    for(int i=0; i<recips.length; i++) { 
     try { 
      recips[i] = new InternetAddress(recips[i].getAddress(), recips[i].getPersonal(), "utf-8"); 
     } catch(UnsupportedEncodingException uee) { 
      throw new RuntimeException("utf-8 not valid encoding?", uee); 
     } 
    } 
    return recips; 
} 

我希望這對某人有用。

1

我知道這是舊的,但這可能會幫助別人。我不明白這個解決方案/黑客可以爲這個問題做些什麼。

這條線在這裏將設置地址recips [0]:

InternetAddress[] recips = InternetAddress.parse(addresses, false); 

,並作爲編碼適用於個人的名字(這是空在這種情況下),此構造這裏改變不了什麼,而不是地址。

new InternetAddress(recips[i].getAddress(), recips[i].getPersonal(), "utf-8"); 

但是,下面的東西會工作,只要郵件服務器可以處理編碼的收件人! (這看起來並不常見......)

recip = MimeUtility.encodeText(recip, "utf-8", "B"); 
InternetAddress[] addressArray = InternetAddress.parse(recip , false); 
msg.addRecipients(MimeMessage.RecipientType.TO, addressArray); 
相關問題