一千萬個為什麽

搜索

將javax.mail.internet.MimeMessage發送給具有非ASCII名稱的收件人?

我正在編寫一段需要向非ASCII名稱用戶發送郵件的Java代碼。我已經想出如何使用UTF-8作為正文,主題行和通用標題,但我仍然堅持收件人

Here's what I'd like in the "To:" field: "ウィキペディアにようこそ" . This lives (for our purposes today) in a String called recip.

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

我該怎麽發送這條消息?


這是我處理其他組件的方式:

  • Body HTML: msg.setText(body, "UTF-8", "html");
  • Headers: msg.addHeader(name, MimeUtility.encodeText(value, "utf-8", "B"));
  • Subject: msg.setSubject(subject, "utf-8");

最佳答案

呃,用一個愚蠢的黑客得到它:

/**
 * 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

我希望這對某人有用。

轉載註明原文: 將javax.mail.internet.MimeMessage發送給具有非ASCII名稱的收件人?