将javax.mail.internet.MimeMessage发送给具有非ASCII名称的收件人?

tre*_*ell 5 java email unicode mime header

我正在编写一段需要向非ASCII名称用户发送邮件的Java代码.我已经弄清楚如何使用UTF-8作为正文,主题行和通用标题,但我仍然坚持收件人.

这是我在"To:"字段中想要的内容:"????????????" <foo@example.com>.它(在我们今天的目的)生活在一个名为String的字符串中recip.

  • msg.addRecipients(MimeMessage.RecipientType.TO, recip)"?????S]" <foo@example.com>
  • 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");

tre*_*ell 5

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

/**
 * 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;
}
Run Code Online (Sandbox Code Playgroud)

我希望这对某人有用.