---
title: Guide On How To Receive Emails Using Java Mail API - Lavish Jain - Medium
updated: 2024-06-03 19:12:01Z
created: 2024-06-03 19:12:01Z
source: >-
  https://medium.com/@lavishj77/guide-on-how-to-receive-emails-using-java-mail-api-a518bf172547
---

<img width="44" height="44" src="../_resources/0_3mEEw-IS7L-PM-xk_e624e454aebf4f1ca66a0c00de15957.png"/>](https://medium.com/@lavishj77?source=post_page-----a518bf172547--------------------------------)

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.

![](../_resources/1__Usha0H-gdP74T74c0gDMg_5468b0edb3284e9a8d0ef2a8f.jpeg)

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.

<a id="fed9"></a>package com.service.email;<a id="82bb"></a>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;<a id="fed8"></a>@Service  
public class ReadInboundEmailService {<a id="54b2"></a>private static final Logger logger = LoggerFactory.getLogger(ReadInboundEmailService.class);<a id="a33c"></a>public void readInboundEmails(){<a id="f572"></a>**//create session object**  
Session session =this.getImapSession();  
try{<a id="46d7"></a>**//connect to message store**  
Store store = session.getStore("imap");  
store.connect(&lt;HOSTNAME&gt;, &lt;PORT&gt;, &lt;USERNAME&gt;, &lt;PASSWORD&gt;);<a id="dccc"></a>**//open the inbox folder**  
IMAPFolder inbox = (IMAPFolder)store.getFolder("INBOX");  
inbox.open(Folder.READ_WRITE);<a id="ca48"></a>**//fetch messages**  
Message\[\] messages = inbox.getMessages();<a id="6e4a"></a>**//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();  
}  
}<a id="9c97"></a>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());  
}  
}<a id="a865"></a>private Session getImapSession(){<a id="ccfb"></a>Properties props = new Properties();<a id="dfb9"></a>props.setProperty("mail.store.protocol","imap");  
props.setProperty("mail.debug", "true");  
props.setProperty("mail.imap.host",&lt;HOST&gt;);  
props.setProperty("mail.imap.port", &lt;PORT&gt;);  
props.setProperty("mail.imap.ssl.enable","true");  
Session session = Session.getDefaultInstance(props, null);<a id="8980"></a>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.***