--- title: >- Java mail IMAP list example - List all the email addresses in an IMAP mailbox | alvinalexander.com updated: 2024-06-03 19:13:23Z created: 2024-06-03 19:13:23Z source: >- https://alvinalexander.com/blog/post/java/i-need-get-all-of-my-email-addresses-out-of-imap-mailbox/ --- By Alvin Alexander. Last updated: March 12, 2018 Java Mail (JavaMail) IMAP FAQ: Can you show me how to get a list of all the email addresses in an IMAP mailbox using the Java Mail API (JavaMail API)? Sure. Here's the source code for a Java mail (JavaMail) program that extracts all of the "from" fields out of a specified mailbox. This works for both POP3 and IMAP mailboxes. Before going to the code, note the cool use of a `TreeSet` (`java.util.TreeSet`) in this example. Based on our offline discussion, you mentioned that you really want is this: 1. Only the unique email addresses, and 2. The addresses sorted alphabetically. Therefore, a TreeSet is a great data type for this purpose. ## ![Ezoic](../_resources/ezoicbwa_3db014528c7e452480e81686ac4ece27.png "ezoic")My JavaMail IMAP email address list program With no further ado, here is the source code for my JavaMail email address list/extractor: import javax.mail.\*; import javax.mail.internet.\*; import java.util.\*; import java.io.\*; /\*\* \* My JavaMail email address extractor. \* A JavaMail API example. \* @author alvin alexander, alvinalexander.com. \*/ public class AddressExtractor { public static void main(String\[\] args) { Properties props = new Properties(); String host = args\[0\]; String username = args\[1\]; String password = args\[2\]; //String provider = "pop3"; String provider = "imap"; try { //Connect to the server Session session = Session.getDefaultInstance(props, null); Store store = session.getStore(provider); store.connect(host, username, password); //open the inbox folder Folder inbox = store.getFolder("INBOX"); inbox.open(Folder.READ_ONLY); // get a list of javamail messages as an array of messages Message\[\] messages = inbox.getMessages(); TreeSet treeSet = new TreeSet(); for(int i = 0; i < messages.length; i++) { String from = getFrom(messages\[i\]); if ( from!=null) { from = removeQuotes(from); treeSet.add(from); } } Iterator it = treeSet.iterator(); while ( it.hasNext() ) { System.out.println("from: " + it.next()); } //close the inbox folder but do not //remove the messages from the server inbox.close(false); store.close(); } catch (NoSuchProviderException nspe) { System.err.println("invalid provider name"); } catch (MessagingException me) { System.err.println("messaging exception"); me.printStackTrace(); } } private static String getFrom(Message javaMailMessage) throws MessagingException { String from = ""; Address a\[\] = javaMailMessage.getFrom(); if ( a==null ) return null; for ( int i=0; i