Read Emails from Inbox

You can use javax.mail.Store to connect, query, and retrieve messages from an Internet Message Access
Protocol (IMAP) e-mail account.

Following code connects to an IMAP account, retrieves the recent five messages from that IMAP account, and marks those five messages as “read”.

We have a settings.properties file in our classpath to store email server’s properties

mail.smtp.host=smtp.gmail.com
mail.smtp.socketFactory.port=465
mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
mail.smtp.auth=true
mail.smtp.port=465

CheckingEmail.java

package com.bharat.examples.mail;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;

public class CheckingEmail {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {

		Properties props = new Properties();
		try {
			props.load(new FileInputStream(new File("settings.properties")));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}

		Session session = Session.getDefaultInstance(props, null);

		Store store = session.getStore("imaps");
		store
				.connect("smtp.gmail.com", "yourEmailId@gmail.com",
						"put your password here");
		System.out.println(store);

		Folder inbox = store.getFolder("inbox");
		inbox.open(Folder.READ_WRITE); // Folder.READ_ONLY
		int messageCount = inbox.getMessageCount();
		System.out.println("Total Messages" + messageCount);
		int startMessage = messageCount - 5;
		int endMessage = messageCount;

		if (messageCount < 5) {
			startMessage = 0;
		}

		Message[] messages = inbox.getMessages(startMessage, endMessage);

		for (Message message : messages) {

			boolean isMessageRead = true;

			for (Flags.Flag flag : message.getFlags().getSystemFlags()) {
				if (flag == Flags.Flag.SEEN) {
					isMessageRead = true;
					break;
				}
			}

			message.setFlag(Flags.Flag.SEEN, true);
			System.out.println(message.getSubject() + " "
					+ (isMessageRead ? " [READ]" : " [UNREAD]"));

		}

		inbox.close(true);
		System.out.println("Done....");
		store.close();
	}
}

A Store object allows you to access e-mail mailbox information. By creating a store and then requesting the “Inbox” folder, you have access to the messages in the main mailbox of your IMAP account. With the folder object, you can request to download the messages from the inbox. To do so, you use the getMessages(start, end) method. The inbox also provides a getMessageCount() method that returns count of mail messages in your inbox. Note that messages start with index 1.

Each message has a set of Flags which can be retrieved using message.getFlags().getSystemFlags()

You can check your message’s Flag against above listed flag constants to check the status and take action accordingly. For eg. in our code above we read top 5 messages and mark it “read” using message.setFlag(Flags.Flag.SEEN, true). To set meesage flags you need to open “folder” in read-write mode using inbox.open(Folder.READ_WRITE).

Message body can be retrieved using message.getContent() method.

At the end of all this you close your inbox folder using inbox.close(true).

For sending email refer tutorial at Sending Email using Java Mail API

Advertisements

, , ,

  1. #1 by Sarada Prasad Sahu on January 17, 2013 - 8:15 am

    Its so help full to me…….

  2. #2 by aylen on June 20, 2013 - 10:45 pm

    hi. i know this is far fetched, but is there a way i can implement this using vb.net?

  3. #3 by nilayvishwakarma on January 17, 2015 - 9:30 pm

    Please be noted that startMessage = 0 will throw error. startMessage must be 1

  4. #4 by Pawan on December 19, 2015 - 7:23 am

    Nice stuff!!!
    I want to know emailds from undelivered mails while showing inbox . I there any technique in java please help

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: