Snippet: Simple One-Minute IMAP Client
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 Create a new Maven project mvn archetype:create -DgroupId=com.hascode.imap -DartifactId=imap-client Edit your pom.xml and add some dependencies <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.hascode.imap</groupId> <artifactId>imap-client</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.8.1</version> </dependency> <dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.2</version> </dependency> </dependencies> </project> Creating the E-Mail Client Create a package .. something like com.hascode.imap.client ;) 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){ this.host = 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"); System.out.println("connect.."); store.connect(this.host, this.userName, this.password); System.out.println("get default folder .."); Folder folder = store.getDefaultFolder(); folder = folder.getFolder("inbox"); folder.open(Folder.READ_ONLY); System.out.println("reading messages.."); Message[] messages = folder.getMessages(); for(Message m:messages){ System.out.println(m.getSubject()); } return false; } } ...