Reading New Emails from Java Applications

Sometimes we only want to check new emails received, we commonly see this functionality in email client where in we open the email client in morning and we see few emails in black bold text denoting new emails received. In this articles we will learn on how we can identify new emails received in our mailbox using java.

Email Exchange Servers can be POP3 and IMAP, by default we use POP3. Every email have certain flags set by which we can identify the new emails received but these functionality is not available in POP3 servers; you will have to use IMAP servers. But there are alternatives to read new emails received in POP3 servers as well but that would required some processing and storing the email ids received at local end.
Various Flags ssed in Emails are SEEN, RECENT, DELETED, ANSWERED, DRAFT, FLAGGED, USER; but now we are going to concentrate on SEEN and ANSWERED one used for checking new emails.

FTP Upload in Java

Check Unread Unread Emails in Java:

import javax.mail.internet.MimeMultipart
import javax.mail.AuthenticationFailedException
import javax.mail.Folder
import javax.mail.FolderClosedException
import javax.mail.FolderNotFoundException
import javax.mail.Message
import javax.mail.Multipart
import javax.mail.NoSuchProviderException
import javax.mail.Part
import javax.mail.ReadOnlyFolderException
import javax.mail.Session
import javax.mail.Store
import java.io.InputStream
import java.io.File
import java.io.BufferedOutputStream
import java.io.BufferedInputStream
import java.io.FileOutputStream
import javax.mail.Flags
import javax.mail.StoreClosedException
import javax.mail.internet.InternetAddress
class ReadEmail {
	private Session sessioned = null;
	private Store store = null;
	private Folder folder = null;
	private Message message = null;
	private Message[] messages = null;
	private Object messagecontentObject = null;
	private String sender = null;
	private String subject = null;
	private Multipart multipart = null;
	private Part part = null;
	private String contentType = null;
	ReadEmail() {
		//Default Constructor
	}
	void processEmail() {
		sessioned = Session.getDefaultInstance(System.getProperties(),null);
		store = sessioned.getStore("imap");
		store.connect([HOSTNAME], [USERNAME],[PASSWORD]);
		// Get a handle on the default folder
		folder = store.getDefaultFolder();
		// Retrieve the "Inbox"
		folder = folder.getFolder("inbox");
		//Reading the Email Index in Read / Write Mode
		folder.open(Folder.READ_WRITE);
		// Retrieve the messages
		messages = folder.getMessages();
		if (messages.length == 0) {
			System.out.println("No Message to Read
"); } else { System.out.println("Total Messages Found:" + messages.length + "
"); } // Loop over all of the messages for (int messageNumber = 0; messageNumber < messages.length; messageNumber++) { // Retrieve the next message to be read message = messages[messageNumber]; Flags flags = message.getFlags(); if (!message.isSet(Flags.Flag.SEEN) && !message.isSet(Flags.Flag.ANSWERED)) { //Here you will read all the email content which are unread } } } public static void main(String args[]) { ReadEmail re = new ReadEmail(); re.processEmail(); } }


Related Articles:

About Hitesh Agrawal

Wait... checking
Tagged . Bookmark the permalink.

4 Responses to Reading New Emails from Java Applications

  1. Ohw great tutorial I will give it a try.. Thanks!

  2. why to you call
    Flags flags = message.getFlags();
    since you don’t use the flags variable?

    Also you open the folder read_write but don’t set any flags etc.

  3. ravi gupta says:

    thanks but someone may plz tell how to get or download only those mails on my PC which are unread?here in this code we are retrieving all messages.i don’t want that.

  4. sonia says:

    thanks for this tutorial
    i want to ask you about hostname
    if i use gmail, the host name is imap.gmail.com?????
    i don’t no why there is an exception when i want to run the java code

    exception at this line:
    store.connect(“imap.gmail.com”, “USERNAME”,”PASSWORD”);

    Exception in thread “main” javax.mail.MessagingException: Connection timed out: connect;
    nested exception is:
    java.net.ConnectException: Connection timed out: connect
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:618)
    at javax.mail.Service.connect(Service.java:291)
    at javax.mail.Service.connect(Service.java:172)
    at cueuj.ReadEmail.processEmail(ReadEmail.java:58)
    at cueuj.ReadEmail.main(ReadEmail.java:84)
    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    at java.net.Socket.connect(Socket.java:529)
    at java.net.Socket.connect(Socket.java:478)
    at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:284)
    at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:227)
    at com.sun.mail.iap.Protocol.(Protocol.java:109)
    at com.sun.mail.imap.protocol.IMAPProtocol.(IMAPProtocol.java:104)
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:585)
    … 4 more
    Java Result: 1

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>