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; } }
-
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 { c.getMail(); } catch (MessagingException e) { e.printStackTrace(); } } }
Debugging an E-Mail Session
If something goes wrong – use the debugging feature in the session object:
session.setDebug(true);
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: “https://www.hascode.com/2012/07/integration-testing-imap-smtp-and-pop3-with-greenmail/[Integration Testing IMAP, SMTP and POP3 with GreenMail]“.