gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 19:58:51 25 4
gpt4 key购买 nike

我正在编写一段 Java 代码,需要向具有非 ASCII 名称的用户发送邮件。我已经弄清楚如何将 UTF-8 用于正文、主题行和通用 header ,但我仍然停留在收件人上。

这是我希望“收件人:”字段中的内容:"ウィキペディアにようこそ" <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");
  • header :msg.addHeader(name, MimeUtility.encodeText(value, "utf-8", "B"));
  • 主题:msg.setSubject(subject, "utf-8");

最佳答案

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

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

我希望这对某人有用。

关于java - 将 javax.mail.internet.MimeMessage 发送给非 ASCII 名称的收件人?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2656478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com