Guide On How To Receive Emails Using Java Mail API

Lavish Jain
2 min readMay 3, 2020

Hi there, this is the first article of a set of two articles in which I am going to discuss about basics of how to receive and read emails from a IMAP server’s inbox using java mail API. In the second article I will write about how to receive and read emails on multiple mailboxes simultaneously and in real time.

Java Mail API

Java Mail is an API used to compose, send, receive and read emails.
The javax.mail package contains the core classes of Java Mail API.
For each user account server has a store which contains all emails. Store is divided into multiple folders and each folder contains categorical emails. “Inbox” folder is the primary folder where all the incoming emails are stored.

Java Mail API provides three corresponding classes Store, Folder and Message

Steps to Connect to Server and Read Emails

  1. Create a session to initiate a working session with the server.
  2. Obtain a store from the session by a specific protocol (IMAP or POP3).
  3. Connect to the store using credentials (username and password).
  4. Get inbox folder from the store and open it.
  5. Retrieve messages from the folder.
  6. Close the folder.
  7. Close the store.
package com.service.email;import java.util.Map;
import java.util.Properties;
import javax.mail.AuthenticationFailedException;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.sun.mail.iap.ProtocolException;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.protocol.IMAPProtocol;
import javax.mail.Message;
@Service
public class ReadInboundEmailService {
private static final Logger logger = LoggerFactory.getLogger(ReadInboundEmailService.class);public void readInboundEmails(){//create session object
Session session =this.getImapSession();
try{
//connect to message store
Store store = session.getStore("imap");
store.connect(<HOSTNAME>, <PORT>, <USERNAME>, <PASSWORD>);
//open the inbox folder
IMAPFolder inbox = (IMAPFolder)store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
//fetch messages
Message[] messages = inbox.getMessages();
//read messages
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();
Address[] toList = msg.getRecipients(RecipientType.TO);
Address[] ccList = msg.getRecipients(RecipientType.CC);
String contentType = msg.getContentType();
}
}
catch (AuthenticationFailedException e){
logger.error("Exception in reading EMails : " +e.getMessage());
}
catch (MessagingException e) {
logger.error("Exception in reading EMails : " +e.getMessage());
}
catch (Exception e) {
logger.error("Exception in reading EMails : " +e.getMessage());
}
}
private Session getImapSession(){Properties props = new Properties();props.setProperty("mail.store.protocol","imap");
props.setProperty("mail.debug", "true");
props.setProperty("mail.imap.host",<HOST>);
props.setProperty("mail.imap.port", <PORT>);
props.setProperty("mail.imap.ssl.enable","true");
Session session = Session.getDefaultInstance(props, null);
session.setDebug(true);
return session;
}
}

Till here we have just seen how to setup process so that we can connect to the mailbox folder and start fetching the emails.
This was in a way preparation for understanding next article in which we will dive deep into how to read emails in real time that too from multiple mailboxes simultaneously and will also process mail content with inline images as well as attachments.

--

--