如何向具有非ASCII名称的收件人发送javax.mail.internet.MimeMessage?

6
我正在编写一段Java代码,需要向名称中包含非ASCII字符的用户发送电子邮件。我已经知道如何使用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.setSubject(subject, "utf-8");
  • 头: msg.addHeader(name, MimeUtility.encodeText(value, "utf-8", "B"));

相关问题和解决方案:https://dev59.com/LFbTa4cB1Zd3GeqP7yT2#5650455 - Abdull
3个回答

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

我希望这对某些人有所帮助。

0

我知道这很老,但这可能会帮助其他人。我不明白那个解决方案/黑客如何为该问题做出任何贡献。

这里的这行代码将设置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);

个人名称正是 OP 想要转换的部分。因此,在这种情况下它不应该为空,并且将由扩展构造函数进行编码。 - Martina

0

对于那些想要转换邮件接收者的人:如果你正在使用InternetAddress.toString(),只需将其更改为InternetAddress.toUnicodeString()

InternetAddress.toString(message.getFrom()) = =?iso-8859-3?Q?Alican_Bal=B9k?= InternetAddress.toUnicodeString(message.getFrom()) = "Alican Balık"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接