Parse RFC 2822 Email Addresses in Java

As many people do not know, email addresses require the library to parse. Simple regular expressions like @(.*) Are not enough. Email addresses may contain comments, which may contain @ characters, breaking simple regular expressions.

There is a Node.js library that parses the addresses of RFC 2822:

 var address = addresses[0]; console.log("Email address: " + address.address); console.log("Email name: " + address.name()); console.log("Reformatted: " + address.format()); console.log("User part: " + address.user()); console.log("Host part: " + address.host()); 

which is an almost direct port of the perl Mail::Address module.

This is what I would expect to exist in the Java class InternetAddress , but it does not break anything further than the full address, which may include, for example, user@gmail.com . But I'm trying to extract the part of gmail.com in which it does not include the method.

I am surprised that I cannot find a common library that solves this, but probably many people have this problem. How can this be solved using the library or not?

+4
source share
2 answers

If you just need to get the domain part from the email address (be aware of the mail groups, since they do not have @), you can do this as follows:

 int index = " user@domain.com ".lastIndexOf("@"); String domain = " user@domain.com ".substring(index+1); 

I used lastIndexOf here, because by RFC2822 an email address can contain more than one @ character (if it is escaped). If you want to skip distribution groups, the InternetAddress class has an isGroup () method

PS It could also be that the address contains routing information:

 @donald.mit.edu,@mail.mit.edu: peter@hotmail.com 

Or address literals:

 peter@ [192.168.134.1] 
+1
source

In most cases, there is no need to split the address into its component parts, since you cannot do anything with the parts. Assuming you have an urgent need, there are libraries that will perform a more thorough check than JavaMail does. Here I found quickly. I am sure there are others.

0
source

Source: https://habr.com/ru/post/1499491/


All Articles