The previous tutorial explains to send email using Javamail API. Now lets see how to read/retreive email in your inbox using Javamail API. Its very simple, this tutorial explains this step by step. If you have not configured Javamail API in your IDE, please download it from here and get it configured only then you will be able to run this program.
First we need to define the protocol for processing emails.
SMTP - is the protocol to send email
POP3 - is the protocol to receive emails
IMAP- IMAP is an acronym for Internet Message Access Protocol. Its an advanced protocol for receiving messages.
This property takes two parameters (key, Value) key is "mail.store.protocol" and its value is "imaps" since we are going to read email protocol is defined as "imaps"
This property is used to get a session instance for reading email and its done as shown below in the code.
Session session = Session.getInstance(props, null);
Store - An abstract class that models a message store and its access protocol, for storing and retrieving messages. Store provides many common methods for naming stores, connecting to stores, and listening to connection events.
We will be making use of connect(String host,String user,String password) method to connect to specified host and get access to Inbox.
Store store = session.getStore();
store.connect("imap.gmail.com", "yourEmailId@gmail.com", "password");
Folder inbox = store.getFolder("INBOX");
Then we need to open the required folder in Read mode.
inbox.open(Folder.READ_ONLY);
Summary: So far we have created a session and connected to gmail host with our username and password and got read access to Inbox.
We are almost done, now get access to your email using 'Message' class as shown below and typecast the content of the mail to Multipart to read the body of the email.
Message msg = inbox.getMessage(1);
Here 1 indicates the first email received in your inbox and getMessageCount() will give you the number of emails in your inbox. So read the latest email use,
Message msg = inbox.getMessage(inbox.getMessageCount());

Copyright © 2011 - All Rights Reserved - Softron.in
Template by Softron Technology