简体   繁体   中英

InternetAddress only the email address without name?

I'm working on a IMAP application with Java, and I want to retrieve only the email address without the name. Here is the relevant code I'm using.

Message[] msg = folder.getMessages();
for (int i = 0; i < msg.length; i++)
{
  if (!msg[i].isSet(Flag.SEEN))
  {
    EmailSenderInfo emailSenderInfo = new EmailSenderInfo();                            
    String from = InternetAddress.toString(msg[i].getFrom());
  }
}

When I print the variable "from", it prints something like below

name <emailaddress@gmail.com>

How can I only get the email address without the name?

The getFrom method returns an array of Address objects, which will actually be InternetAddress objects. Normally there's only one From address so you can just use the first element in the array. Then use the InternetAddress.getAddress method:

 InternetAddress ia = (InternetAddress)msg[i].getFrom()[0];
 String from = ia.getAddress();

Whith pattern matching :

import java.util.regex.Pattern;
import java.util.regex.Matcher;


Pattern pattern = Pattern.compile("<(.*?)>");
Matcher matcher = pattern.matcher("name <emailaddress@gmail.com>");

if (matcher.find())
{
    System.out.println(matcher.group(1));  // prints "emailaddress@gmail.com"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM