Receiving Email using POP3 protocol

In this post under Java Mail, I will explain with example how to receive email using POP3 protocal.

The steps involved are

1) Setup the properties object
2) Create a Session object
3) Get a Store instance using Session’s getStore method
4) Connect to the store using email address and application password
5) Get the inbox folder from the store
6) Open the inbox folder and get the messages as an array.

Below is the example

Main class

1  package package6;
3  import java.util.Properties;
5  import javax.mail.Folder;
6  import javax.mail.Message;
7  import javax.mail.MessagingException;
8  import javax.mail.NoSuchProviderException;
9  import javax.mail.Session;
10 import javax.mail.Store;
12 public class Example6 {
13     public static void main(String[] args) throws NoSuchProviderException, MessagingException {
14         Properties properties = new Properties();
15         Session session = Session.getInstance(properties);
16         Store store = session.getStore("pop3s");
17         store.connect("", "***********************", "**************");
18         Folder inbox = store.getFolder("INBOX");
20         Message[] messages = inbox.getMessages();
21         for(int i = 0; i < messages.length; i++) {
22             Message message = messages[i];
23             System.out.println(message.getSubject());
24         }
25         inbox.close(false);
26         store.close();
27     }
28 }

In the above code, at line 14, we setup Properties object

At line 15, we get the Session instance using getInstance method and passing Properties instance created at line 14, as an argument to the method.

At line 16, we are getting a Store instance that implements the specified protocol, which in this cases is POP3. Store represents a message store created in-memory.

At line 17, we connect to the Store using the email address and application password.

In Gmail we have “INBOX” folder, so at line 18, we get that folder using Store’s getFolder method and passing the folder name as argument.

At line 19, we open the “INBOX” folder as read only

At line 20, we get the messages in the folder as an array of messages.

From line 21 to 24, we loop through each message and display the each message subject.

At line 25, we close the inbox folder. Note we passing false as an argument, this is to inform mail server not to expunge any mails. If true, while closing the folder, all mails marked for deletion are expunged.

At line 26, we close the Store instance.

Leave a Reply