This article walks through steps to download e-mail messages from a POP3/IMAP server’s inbox, using JavaMail API. The following picture depicts how messages are logically stored on the server:

mail store

we can see, for each user account, the server has a store which is the storage of user’s messages. The store is divided into folders, and the “inbox” folder is the primarily folder which contains e-mail messages. A folder can contain both messages and sub-folders.

Speaking of JavaMail API‘s language, it provides three corresponding classes: Store, Folder and Message.

-          A Store object can be obtained from the current session by invoking the method getStore(String protocol) of Session class. Connecting to the Store by calling its method connect(String user, String pass), disconnecting by calling its close() method.

-          A Folder object can be obtained from the store by invoking the getFolder(String folderName) method. For a regular mail box, the folder name must be “inbox” (case-insensitive). The most important methods of the Folder class are:

          • open(int mode): Opens the folder either in READ_ONLY mode or READ_WRITE mode.
          • getMessages(): Retrieves an array of Message objects which are marked un-read in the folder. A Message object may be a lightweight reference, and its detailed content will be filled up on demand.
          • close(boolean expunge): Closes the folder, and permanently remove all messages which are marked delete, if expunge is true.

-          A Message object represents an e-mail message. To get detailed attributes of a message, the following methods can be called on the Message object:

          • Address[] getFrom(): returns a list of senders in From attribute of the message.
          • Address[] getRecipients(Message.RecipientType type): gets recipient addresses of the message, type can be either TO or CC.
          • String getSubject(): gets subject of the message.
          • Date getSentDate(): gets date and time when the message was sent.
          • Object getContent(): gets content of the message.
Typically, the steps to connect to a server and download new e-mail messages are as follows:

-          Prepare a Properties object which holds server settings such as host, port, protocol…

-          Create a session to initiate a working session with the server.

-          Obtain a store from the session by a specific protocol (IMAP or POP3). IMAP is recommended.

-          Connect to the store using a credential (username and password).

-          Gets inbox folder from the store.

-          Open the inbox folder.

-          Retrieve messages from the folder.

-          Fetch details for each message.

-          Close the folder.

-          Close the store.

And following is code of a sample program:

package net.codejava.mail;

import java.util.Properties;

import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

/**
 * This program demonstrates how to get e-mail messages from a POP3/IMAP server
 *
 * @author www.codejava.net
 *
 */
public class EmailReceiver {

	/**
	 * Returns a Properties object which is configured for a POP3/IMAP server
	 *
	 * @param protocol either "imap" or "pop3"
	 * @param host
	 * @param port
	 * @return a Properties object
	 */
	private Properties getServerProperties(String protocol, String host,
			String port) {
		Properties properties = new Properties();

		// server setting
		properties.put(String.format("mail.%s.host", protocol), host);
		properties.put(String.format("mail.%s.port", protocol), port);

		// SSL setting
		properties.setProperty(
				String.format("mail.%s.socketFactory.class", protocol),
				"javax.net.ssl.SSLSocketFactory");
		properties.setProperty(
				String.format("mail.%s.socketFactory.fallback", protocol),
				"false");
		properties.setProperty(
				String.format("mail.%s.socketFactory.port", protocol),
				String.valueOf(port));

		return properties;
	}

	/**
	 * Downloads new messages and fetches details for each message.
	 * @param protocol
	 * @param host
	 * @param port
	 * @param userName
	 * @param password
	 */
	public void downloadEmails(String protocol, String host, String port,
			String userName, String password) {
		Properties properties = getServerProperties(protocol, host, port);
		Session session = Session.getDefaultInstance(properties);

		try {
			// connects to the message store
			Store store = session.getStore(protocol);
			store.connect(userName, password);

			// opens the inbox folder
			Folder folderInbox = store.getFolder("INBOX");
			folderInbox.open(Folder.READ_ONLY);

			// fetches new messages from server
			Message[] messages = folderInbox.getMessages();

			for (int i = 0; i < messages.length; i++) {
				Message msg = messages[i];
				Address[] fromAddress = msg.getFrom();
				String from = fromAddress[0].toString();
				String subject = msg.getSubject();
				String toList = parseAddresses(msg
						.getRecipients(RecipientType.TO));
				String ccList = parseAddresses(msg
						.getRecipients(RecipientType.CC));
				String sentDate = msg.getSentDate().toString();

				String contentType = msg.getContentType();
				String messageContent = "";

				if (contentType.contains("text/plain")
						|| contentType.contains("text/html")) {
					try {
						Object content = msg.getContent();
						if (content != null) {
							messageContent = content.toString();
						}
					} catch (Exception ex) {
						messageContent = "[Error downloading content]";
						ex.printStackTrace();
					}
				}

				// print out details of each message
				System.out.println("Message #" + (i + 1) + ":");
				System.out.println("\t From: " + from);
				System.out.println("\t To: " + toList);
				System.out.println("\t CC: " + ccList);
				System.out.println("\t Subject: " + subject);
				System.out.println("\t Sent Date: " + sentDate);
				System.out.println("\t Message: " + messageContent);
			}

			// disconnect
			folderInbox.close(false);
			store.close();
		} catch (NoSuchProviderException ex) {
			System.out.println("No provider for protocol: " + protocol);
			ex.printStackTrace();
		} catch (MessagingException ex) {
			System.out.println("Could not connect to the message store");
			ex.printStackTrace();
		}
	}

	/**
	 * Returns a list of addresses in String format separated by comma
	 *
	 * @param address an array of Address objects
	 * @return a string represents a list of addresses
	 */
	private String parseAddresses(Address[] address) {
		String listAddress = "";

		if (address != null) {
			for (int i = 0; i < address.length; i++) {
				listAddress += address[i].toString() + ", ";
			}
		}
		if (listAddress.length() > 1) {
			listAddress = listAddress.substring(0, listAddress.length() - 2);
		}

		return listAddress;
	}

	/**
	 * Test downloading e-mail messages
	 */
	public static void main(String[] args) {
		// for POP3
		//String protocol = "pop3";
		//String host = "pop.gmail.com";
		//String port = "995";

		// for IMAP
		String protocol = "imap";
		String host = "imap.gmail.com";
		String port = "993";


		String userName = "your_email_address";
		String password = "your_email_password";

		EmailReceiver receiver = new EmailReceiver();
		receiver.downloadEmails(protocol, host, port, userName, password);
	}
}
In the EmailReceiver class above, the primary method is downloadEmail(), and the two helper methods, getServerProperties() and parseAddresses(). The server information used for testing is Gmail’s IMAP server, and remember to change userName and password to match your account.

 

NOTES:

 

You need to use JavaMail jar files. If you use Maven, add the following dependency to the pom.xml file:

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


This will add the javax.mail-VERSION.jar and activation-VERSION.jar to the project's classpath. If you have to add them manually, download from JavaMail Project page.

 

 

Other JavaMail Tutorials:

 


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Attachments:
Download this file (EmailReceiver.java)EmailReceiver.java[Sample program for downloading e-mail messages]4 kB

Add comment

   


Comments 

#23Iván Hernández Vázqu2023-05-23 18:04
I am using this library in a SpringBoot project, but I am getting this error:

javax.mail.Provider: com.sun.mail.imap.IMAPProvider not a subtype

Any idea about the reason for this error?
Quote
#22Nam2021-04-23 09:12
Hi AkhilChowdary Nallap,
For sending emails in Spring Boot, kindly follow this tutorial: www.codejava.net/.../email-sending-tutorial
Quote
#21AkhilChowdary Nallap2021-04-23 00:32
have u created this project in spring boot
Quote
#20AkhilChowdary Nallap2021-04-22 01:02
is it works on spring boot
Quote
#19Benjamin Tsalkovich2020-01-08 01:50
You need to configure SSL certificate on you Client
Quote