Home > Java > Reading POP3 Mails Using Java

Reading POP3 Mails Using Java

Java provides with set of API called JavaMail that allows you to connect to and read POP3 Emails. This article will show you how we can read POP3 Emails using Java.

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 javax.mail.StoreClosedException;
import javax.mail.internet.InternetAddress;
 
public class readEmails {
 
//Constructor Call
public readEmails() {
   processMail();
}
 
//Responsible for printing Data to Console
private void printData(String data) {
   System.out.println(data);
}
 
public void processMail() {
   Session session = null;
   Store store = null;
   Folder folder = null;
   Message message = null;
   Message[] messages = null;
   Object messagecontentObject = null;
   String sender = null;
   String subject = null;
   Multipart multipart = null;
   Part part = null;
   String contentType = null;
 
   try {
      printData("--------------processing mails started-----------------");
      session = Session.getDefaultInstance(System.getProperties(), null);
 
      printData("getting the session for accessing email.");
      store = session.getStore("pop3");
 
      store.connect("host Name OR IP","username","password");
      printData("Connection established with POP3 server.");
 
      // Get a handle on the default folder
      folder = store.getDefaultFolder();
 
      printData("Getting the Inbox folder.");
 
      // 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();
 
      // Loop over all of the messages
      for (int messageNumber = 0; messageNumber < messages.length; messageNumber++) {
           // Retrieve the next message to be read
	   message = messages[messageNumber];
 
           // Retrieve the message content
           messagecontentObject = message.getContent();
 
           // Determine email type
           if (messagecontentObject instanceof Multipart) {
               printData("Found Email with Attachment");
               sender = ((InternetAddress) message.getFrom()[0]).getPersonal();
 
               // If the "personal" information has no entry, check the address for the sender information
               printData("If the personal information has no entry, check the address for the sender information.");
 
	       if (sender == null) {
	 	   sender = ((InternetAddress) message.getFrom()[0]).getAddress();
		   printData("sender in NULL. Printing Address:" + sender);
	       }
               printData("Sender -." + sender);
 
               // Get the subject information
               subject = message.getSubject();
 
               printData("subject=" + subject);
 
               // Retrieve the Multipart object from the message
               multipart = (Multipart) message.getContent();
 
               printData("Retrieve the Multipart object from the message");
 
               // Loop over the parts of the email
               for (int i = 0; i < multipart.getCount(); i++) {
                    // Retrieve the next part
                    part = multipart.getBodyPart(i);
 
                    // Get the content type
                    contentType = part.getContentType();
 
                   // Display the content type
		   printData("Content: " + contentType);
 
                   if (contentType.startsWith("text/plain")) {
			printData("---------reading content type text/plain  mail -------------");
		   } else {
			// Retrieve the file name
			String fileName = part.getFileName();
			printData("retrive the fileName="+ fileName);
		   }
	      }
	   } else {
	      printData("Found Mail Without Attachment");
	      sender = ((InternetAddress) message.getFrom()[0]).getPersonal();
 
              // If the "personal" information has no entry, check the address for the sender information
	      printData("If the personal information has no entry, check the address for the sender information.");
 
              if (sender == null) {
		sender = ((InternetAddress) message.getFrom()[0]).getAddress();
		printData("sender in NULL. Printing Address:" + sender);
	     }
 
             // Get the subject information
	     subject = message.getSubject();
	     printData("subject=" + subject);
	 }
      }
 
      // Close the folder
      folder.close(true);
 
      // Close the message store
      store.close();
  } catch(AuthenticationFailedException e) {
     printData("Not able to process the mail reading.");
     e.printStackTrace();
  } catch(FolderClosedException e) {
     printData("Not able to process the mail reading.");
     e.printStackTrace();
  } catch(FolderNotFoundException e) {
     printData("Not able to process the mail reading.");
     e.printStackTrace();
  }  catch(NoSuchProviderException e) {
     printData("Not able to process the mail reading.");
     e.printStackTrace();
  } catch(ReadOnlyFolderException e) {
     printData("Not able to process the mail reading.");
     e.printStackTrace();
  } catch(StoreClosedException e) {
     printData("Not able to process the mail reading.");
     e.printStackTrace();
  } catch (Exception e) {
     printData("Not able to process the mail reading.");
     e.printStackTrace();
  }
}
 
//Main  Function for The readEmail Class
public static void main(String args[]) {
    //Creating new readEmail Object
    readEmails readMail = new readEmails();
 
    //Calling processMail Function to read from POP3 Account
    readMail.processMail();
}
 
}

Your email:

 


Code Explanation:

  • processMail() function is the core function responsible for connecting and reading the mails.
  • Here i am reading the INBOX folder of the email account.
  • Also i am reading the emails in READ-WRITE mode that allows me to do read and modify emails at runtime.
  • I am than iterating to the individual messages using for loop.
  • While iterating individual messages i am checking whether the message contains attachment or not.
  • Finally i am closing the email folder and store connection.


Custom Search

Popular Articles:

Share and Enjoy:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DZone
  • email
  • IndianPad
  • LinkedIn
  • Live
  • MySpace
  • Netvibes
  • RSS
  • Technorati
  • Yahoo! Bookmarks
  • Yahoo! Buzz
  • Reddit
  • Add to favorites
  • PDF
  • Twitter
Categories: Java Tags:
  1. Kalyani Bhadekar
    February 27th, 2009 at 03:50 | #1

    I tried using above prog with mail.jar, activation.jar, mailapi.jar in my classpath. The prog got compiled successfully but while running, I got the following as the stacktrace-
    Not able to process the mail reading.
    javax.mail.MessagingException: Connect failed;
    nested exception is:
    java.net.ConnectException: Connection refused: connect
    at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:161)
    at javax.mail.Service.connect(Service.java:288)
    at javax.mail.Service.connect(Service.java:169)
    at com.javaMailSamples.ReadMailFromPOP3Server.processMail(ReadMailFromPOP3Server.java:50)
    at com.javaMailSamples.ReadMailFromPOP3Server.(ReadMailFromPOP3Server.java:22)
    at com.javaMailSamples.ReadMailFromPOP3Server.main(ReadMailFromPOP3Server.java:168)

  2. kundan
    June 16th, 2009 at 05:44 | #2

    hi friend, found your codes quite useful…..thnx a lot 4 it…hey i am trying mark messages read using pop3…is it possible…? i can create a log file or somthing on client side….
    Thanx in advance.
    With Regards,
    kundan

  3. June 20th, 2009 at 13:01 | #3

    The topic is quite hot on the Internet right now. What do you pay the most attention to when choosing what to write ?
    p.s. Year One is already on the Internet and you can watch it for free.

  4. COnza
    August 18th, 2009 at 02:22 | #4

    thanks dear ur code is soooo useful, bt how do u only read mails that are existing nt the new ones????????

  5. ranjith
    January 23rd, 2010 at 12:14 | #6

    i have run the code
    but its giving me the foll error
    what should i write in the place of host name or IP

    C:Java Mail>java readEmails
    ————–processing mails started—————–
    getting the session for accessing email.
    Not able to process the mail reading.
    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 readEmails.processMail(readEmails.java:47)
    at readEmails.(readEmails.java:19)
    at readEmails.main(readEmails.java:165)
    Caused by: java.net.ConnectException: Connection timed out: connect
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.PlainSocketImpl.doConnect(Unknown Source)
    at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    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)
    … 5 more

  6. Nelson
    March 8th, 2010 at 14:52 | #7

    @ranjith
    Hi ranjit you actually should put something like this :
    store.connect(“127.0.0.1″,”your_mail_user_name”,”your_mail_password”);
    store.connect(“localhost”,”your_mail_user_name”,”your_mail_password”);

    The IP number (something like 127.0.0.1) or the host name (like localhost ) where your email server is based.

  7. elango
    August 19th, 2010 at 06:34 | #8

    even when i gave hostname also it shows same errors as ranjith said….
    for my gmail acct i gave “smtp.gmail.com” as host name and my user name and password… same error repeated….

  1. April 3rd, 2010 at 04:56 | #1