现在允许使用带有特殊丹麦语字符(例如 æ ø å)的域,但我不能强制 java 邮件接受它。
@Test()
public void testMailAddressWithDanishCharacters1() throws AddressException, UnsupportedEncodingException {
InternetAddress cAddress = new InternetAddress( "test@testæxample12345123.com", null, "utf-8" );
System.out.println( cAddress.toString() );
cAddress.validate();
}
@Test()
public void testMailAddressWithDanishCharacters2() throws AddressException, UnsupportedEncodingException {
InternetAddress cAddress = new InternetAddress( "test@testæxample12345123.com", false );
System.out.println( cAddress.toString() );
cAddress.validate();
}
@Test()
public void testMailAddressWithDanishCharacters3() throws AddressException, UnsupportedEncodingException {
InternetAddress cAddress = new InternetAddress( "test@testæxample12345123.com", true );
System.out.println( cAddress.toString() );
cAddress.validate();
}
所有测试都在 InternetAddress 的构造函数或 validate() 方法中失败。我如何处理域中的这些特殊丹麦字符。我敢打赌其他国家的域与 javamail InternetAddress 中的电子邮件存在同样的问题。
最佳答案
目前邮件服务器一般不接受本地部分的非 ASCII 字符,IDN 仅支持域部分(“@”符号之后)。
为了仅使用 java.net.IDN 类对域部分进行编码,我使用以下 Util。
(代码未在生产环境中测试,但应该可以)
import java.net.IDN;
public class IDNMailHelper {
public static String toIdnAddress(String mail) {
if (mail == null) {
return null;
}
int idx = mail.indexOf('@');
if (idx < 0) {
return mail;
}
return localPart(mail, idx) + "@" + IDN.toASCII(domain(mail, idx));
}
private static String localPart(String mail, int idx) {
return mail.substring(0, idx);
}
private static String domain(String mail, int idx) {
return mail.substring(idx + 1);
}
}
关于Java邮件 : "Domain contains control or whitespace in string" errormessage because of domain with Danish characters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5483706/