Introduction

In this short tutorial, we'll show how to read an email in Java and also how to get email sender data in Java using javax.mail library. In the code sample below, we'll be reading Gmail, count received unread messages, and print sender data on the console.

Implementation

Let's first add javax.mail Maven dependency that will help us with reading our mail:

<dependency>
    <groupId>com.sun.mail</groupId>	
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>

Let's see how to check the contents of Inbox and read sender data from email:

package com.javahowtos.javaemail.demo;

import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.search.FlagTerm;

public class JavaEmailExample {
    public static void main(String[] args) {
        getEmailMessages("imap.gmail.com", "youremail@gmail.com", "yourpass");
    }

    public static void getEmailMessages(String host, String username, String password) {
        try {
            // create properties
            Properties properties = new Properties();

            properties.put("mail.imap.host", host);
            properties.put("mail.imap.port", "993");
            properties.put("mail.imap.starttls.enable", "true");
            properties.put("mail.imap.ssl.trust", host);

            Session emailSession = Session.getDefaultInstance(properties);

            // create the imap store object and connect to the imap server
            Store store = emailSession.getStore("imaps");
            store.connect(host, username, password);
            // create the inbox object and open it
            Folder inbox = store.getFolder("Inbox");
            inbox.open(Folder.READ_WRITE);

            // retrieve the messages from the folder in an array and print it
            Message[] messages = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
            System.out.println("messages.length---" + messages.length);
            for (Message message : messages) {
                InternetAddress sender = (InternetAddress) message.getFrom()[0];
                System.out.println("Sender name : " + sender.getPersonal());
                System.out.println("Sender email : " + sender.getAddress());
            }
            inbox.close(false);
            store.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Since it's more useful to extract email and sender name separately from the Address object, cast Address array to InternetAddress array.

In case you're getting a message like this while executing this code, please check your firewall and antivirus since they are probably blocking the request:

javax.mail.MessagingException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target;
  nested exception is:
	javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:742)
	at javax.mail.Service.connect(Service.java:366)
	at javax.mail.Service.connect(Service.java:246)
	at filemanagement.Class2.getEmailMessages(Class2.java:33)
	at filemanagement.Class2.main(Class2.java:16)
Caused by: javax.net.ssl.SSLHandshakeException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

In my case Avast was blocking the request towards Gmail, so everything worked fine after pausing it.