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

时间:2010-04-16 22:46:08

标签: java email unicode header mime

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

以下是“收件人:”字段中我想要的内容:"ウィキペディアにようこそ" <foo@example.com>。它存在于(今天我们的目的)名为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");

2 个答案:

答案 0 :(得分: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;
}

我希望这对某人有用。

答案 1 :(得分:1)

我知道这是旧的,但这可能对其他人有所帮助。我不明白该解决方案/黑客如何能够解决这个问题。

这一行将设置recips [0]的地址:

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

并且这里的构造函数没有任何改变,因为编码适用于个人名称(在这种情况下为null)而不是地址。

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);