代码之家  ›  专栏  ›  技术社区  ›  Tim has moved to Codidact

是否将javax.mail.internet.mimemessage发送给非ASCII名称的收件人?

  •  5
  • Tim has moved to Codidact  · 技术社区  · 16 年前

    我正在编写一个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.addHeader(name, MimeUtility.encodeText(value, "utf-8", "B"));
    • 主题: msg.setSubject(subject, "utf-8");
    2 回复  |  直到 12 年前
        1
  •  5
  •   Tim has moved to Codidact    16 年前

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

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

    我希望这对某人有用。

        2
  •  1
  •   Marc    12 年前

    我知道这是旧的,但这可能会帮助别人。我不明白那个解决方案/黑客是如何解决这个问题的。

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