Created
May 15, 2023 21:56
-
-
Save JamesBoon/feeb7428b3558d581c0459f7302bd9a5 to your computer and use it in GitHub Desktop.
Create a normalized version of an email address containing UTF8 characters in the domain part according to IDNA2008.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.example; | |
// https://mvnrepository.com/artifact/com.ibm.icu/icu4j/73.1 | |
import com.ibm.icu.text.IDNA; | |
// https://mvnrepository.com/artifact/com.sanctionco.jmail/jmail/1.5.0 | |
import com.sanctionco.jmail.Email; | |
import com.sanctionco.jmail.EmailValidationResult; | |
import com.sanctionco.jmail.JMail; | |
public class IdnEmailExample { | |
private static final IDNA validator = IDNA.getUTS46Instance( | |
IDNA.NONTRANSITIONAL_TO_ASCII | |
| IDNA.NONTRANSITIONAL_TO_UNICODE | |
| IDNA.CHECK_BIDI | |
| IDNA.CHECK_CONTEXTJ | |
| IDNA.CHECK_CONTEXTO | |
| IDNA.USE_STD3_RULES); | |
public static void main(String[] args) { | |
String address = toAscii("you@déjà.VU.straße.example.com"); | |
// Returns: [email protected] | |
if (null == address) { | |
System.out.println("Invalid email address."); | |
} else { | |
System.out.println("Ascii email address: " + address); | |
} | |
} | |
/** | |
* Returns a normalized version of an email address containing | |
* UTF8 characters in the domain part according to IDNA2008. | |
*/ | |
public static String toAscii(String email) { | |
EmailValidationResult result = JMail.validator().validate(email); | |
if (result.isFailure()) { | |
System.out.println("Failure: " + result.getFailureReason()); | |
return null; | |
} | |
Email parsedEmail = result.getEmail().get(); | |
if (parsedEmail.isIpAddress()) { | |
return parsedEmail.normalized(); | |
} | |
IDNA.Info info = new IDNA.Info(); | |
StringBuilder asciiDomain = new StringBuilder(); | |
validator.nameToASCII(parsedEmail.domainWithoutComments(), asciiDomain, info); | |
if (info.hasErrors()) { | |
System.out.println("Errors: " + info.getErrors()); | |
return null; | |
} | |
return parsedEmail.localPartWithoutComments() + "@" + asciiDomain; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment