Snippet: Simple One-Minute IMAP Client

April 3rd, 2010 by

Building a simple IMAP Client that displays the subject of the messages in the “inbox” Folder using Maven (I just like Maven).


Project Setup / Maven

  1. Create a new Maven project
    mvn archetype:create -DgroupId=com.hascode.imap -DartifactId=imap-client
  2. Edit your pom.xml and add some dependencies
    <project xmlns="" xmlns:xsi="" xsi:schemaLocation="">

Creating the E-Mail Client

  1. Create a package .. something like com.hascode.imap.client ;)
  2. Create a simple mail client using javax.mail in a class named ImapClient
    package com.hascode.imap.client;
    import javax.mail.Folder;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Session;
    import javax.mail.Store;
    public class ImapClient {
    private Session session = null;
    private Store store = null;
    private String host = null;
    private String userName = null;
    private String password = null;
    public ImapClient(String host, String userName, String password){ = host;
    this.userName = userName;
    this.password = password;
    public boolean getMail() throws MessagingException {
    session = Session.getDefaultInstance(System.getProperties(),null);
    //        session.setDebug(true);
    System.out.println("get store..");
    store = session.getStore("imaps");
    store.connect(, this.userName, this.password);
    System.out.println("get default folder ..");
    Folder folder = store.getDefaultFolder();
    folder = folder.getFolder("inbox");;
    System.out.println("reading messages..");
    Message[] messages = folder.getMessages();
    for(Message m:messages){
    return false;
  3. Test the result in an unit test or a test class like this one
    package com.hascode.imap.client;
    import javax.mail.MessagingException;
    public class Main {
    public static void main(String[] args) {
    ImapClient c = new ImapClient("<yourhostname>", "<yourusername>","<yourpassword>");
    try {
    } catch (MessagingException e) {

Debugging an E-Mail Session

If something goes wrong – use the debugging feature in the session object:


Creating an E-Mail Server in Java

If you’re interested in creating an e-mail server in java for testing please feel free to take a look at my tutorial: “Integration Testing IMAP, SMTP and POP3 with GreenMail“.


Tags: , , ,