我正在编写一段Java代码,该代码需要将邮件发送给具有非ASCII名称的用户。我已经弄清楚了如何对正文,主题行和通用标头使用UTF-8,但是我仍然停留在收件人上。
这是我在“收件人:”字段中想要的:"ウィキペディアにようこそ" <[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==?=''
我该怎么发送此消息?
这是我处理其他组件的方式:
msg.setText(body, "UTF-8", "html");
msg.addHeader(name, MimeUtility.encodeText(value, "utf-8", "B"));
msg.setSubject(subject, "utf-8");
gh,它是通过一个愚蠢的骇客获得的:
/**
* 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;
}
我希望这对某人有用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句