Java: Send email to a Non-ASCII email address
email, internationalization, jakarta-mail, java, java-8
Solution
Paweł is essentially right that the addresses should be encoded as UTF-8 if your server supports the SMTPUTF8 extension. Support for SMTPUTF8 is in the JavaMail 1.6 release.
To enable this support, you need to set the JavaMail Session property `mail.mime.allowutf8` to `true`. Be sure to only set it when the mail server supports UTF-8.
For older versions of JavaMail, a possible workaround involves converting the Java Unicode String to a UTF-8 encoded byte array, then creating a Java Unicode String where each byte is a separate iso-8859-1 character. I haven't tried this so I don't know if it will run into other issues.
For example:
address = new String(address.getBytes("utf-8"), "iso-8859-1");
Problem
I want to send an email to a Non-ASCII email address and I am not sure what is the recommended procedure using JDK8. How should I deal with the following email addresses? - Dörte@example.com - test@Sörensen.de - Dörte@Sörensen.de Are there any security considerations to be aware of? Would this sample code be enough? ``` 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); } } ```