How to extract name domain from mail in java

You can extract the domain name from an email address in Java using the following methods:

  1. Using String methods:

    String email = "[email protected]";
    String[] parts = email.split("@");
    String domain = parts[1];

    This will give you the domain name as "example.com".

  2. Using java.net.IDN class:

    String email = "[email protected]";
    IDN idn = new IDN(email, "utf-8");
    String domain = idn.toASCII().substring(idn.toASCII().indexOf('@') + 1);

    This will also give you the domain name as "example.com".

  3. Using a regular expression:

    String email = "[email protected]";
    Pattern pattern = Pattern.compile("@(.*)");
    Matcher matcher = pattern.matcher(email);
    if (matcher.find()) {
     String domain = matcher.group(1);
     System.out.println(domain); // prints "example.com"
    }

    This will also give you the domain name as "example.com".

  4. Using a library like Apache Commons Email:

    String email = "[email protected]";
    Email emailObject = new Email(email);
    String domain = emailObject.getDomain();

    This will give you the domain name as "example.com".

Note that the IDN class is used to handle internationalized domain names (IDNs), which can contain non-ASCII characters. If you're working with plain ASCII domain names, you can use the first method.

Also, be aware that these methods will extract the domain name from the email address, but they won't validate whether the email address is valid or not.