Home > Java, mail, receivemail > Java Code to Receive Mail using JavaMailAPI

Java Code to Receive Mail using JavaMailAPI

Introduction:

In the previous article, we have looked at sending mail with Java Mail API.Sending e-mail was relatively simple with only one protocol (SMTP) to handle. But Reception involves two protocols, POP3 and IMAP. POP3 is the older protocol, which offers a single queue of mail messages as a single inbox. IMAP is the more modern protocol, which presents mail messages as entries in a hierarchy of folders, one of which will be an inbox.

Java Mail comes with Provider implementations for POP3 and IMAP, and the secure versions of those as POP3S and IMAPS.

Prerequisites:

JDK 1.5 and Above

Jar: Mail. jar

Steps involved in receive mail:

Step 1: Define the mail properties (i.e.) Define the protocol, mail server by using the properties class.

Step 2: Create the session for read the mail with the properties which we already defined.

Step 3: Create and connect the store for read the mail.

Step 4: Define and open the folder which we need to read. Open the folder in read-only mode.

Step 5: Search the unread contents in the specified folder and stored it into messages array.

Step 6: Display the messages.

Description of classes and methods :

Store:

An abstract class that models a message store and its access protocol, for storing and retrieving messages.

Methods:

connect -> It is used to connect the store with the mail server store.

getFolder-> It is used to define the folder which will be read. Return Folder class.

Folder:

Folder is an abstract class that represents a folder for mail messages. Folders can contain Messages, other Folders

Methods:

open   -> Method for open the foder.We must define the mode of open.

search -> Method for get the messages. Return type: Message[].

fetch  -> Method for Fetch the details which is represented by FetchProfile.

close  -> Method for close the folder.

FetchProfile:

List the Message attributes that it wishes to prefetch from the server for a range of messages.

Method:

add  ->  Method for add the attributes which we wish to prefetch.

Message:

This class models an email message. This is an abstract class. Message implements the Part interface

A Message object obtained from a folder is just a lightweight reference to the actual message.

Methods:

getContent  ->  Method for get the content of the message.

Code:

/*
 *  This is the code for read the unread mails from your mail account.
 *  Requirements:
 *      JDK 1.5 and above
 *      Jar:mail.jar
 *
 */
package com.info.mail;
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.Flags.Flag;
import javax.mail.search.FlagTerm;

public class MailReader
{
 Folder inbox;

 //Constructor of the calss.
 public MailReader()
 {
 /*  Set the mail properties  */
 Properties props = System.getProperties();
 props.setProperty("mail.store.protocol", "imaps");
 try
 {
 /*  Create the session and get the store for read the mail. */
 Session session = Session.getDefaultInstance(props, null);
 Store store = session.getStore("imaps");
 store.connect("imap.gmail.com","<mail ID> ", "<Password>");

 /*  Mention the folder name which you want to read. */
 inbox = store.getFolder("Inbox");
 System.out.println("No of Unread Messages : " + inbox.getUnreadMessageCount());

 /*Open the inbox using store.*/
 inbox.open(Folder.READ_ONLY);

 /*  Get the messages which is unread in the Inbox*/
 Message messages[] = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));

 /* Use a suitable FetchProfile    */
 FetchProfile fp = new FetchProfile();
 fp.add(FetchProfile.Item.ENVELOPE);
 fp.add(FetchProfile.Item.CONTENT_INFO);
 inbox.fetch(messages, fp);

 try
 {
 printAllMessages(messages);
 inbox.close(true);
 store.close();
 }
 catch (Exception ex)
 {
 System.out.println("Exception arise at the time of read mail");
 ex.printStackTrace();
 }
 }
 catch (NoSuchProviderException e)
 {
 e.printStackTrace();
 System.exit(1);
 }
 catch (MessagingException e)
 {
 e.printStackTrace();
 System.exit(2);
 }
 }

 public void printAllMessages(Message[] msgs) throws Exception
 {
 for (int i = 0; i < msgs.length; i++)
 {
 System.out.println("MESSAGE #" + (i + 1) + ":");
 printEnvelope(msgs[i]);
 }
 }

 /*  Print the envelope(FromAddress,ReceivedDate,Subject)  */
 public void printEnvelope(Message message) throws Exception
 {
 Address[] a;
 // FROM
 if ((a = message.getFrom()) != null)
 {
 for (int j = 0; j < a.length; j++)
 {
 System.out.println("FROM: " + a[j].toString());
 }
 }
 // TO
 if ((a = message.getRecipients(Message.RecipientType.TO)) != null)
 {
 for (int j = 0; j < a.length; j++)
 {
 System.out.println("TO: " + a[j].toString());
 }
 }
 String subject = message.getSubject();
 Date receivedDate = message.getReceivedDate();
 String content = message.getContent().toString();
 System.out.println("Subject : " + subject);
 System.out.println("Received Date : " + receivedDate.toString());
 System.out.println("Content : " + content);
 getContent(message);
 }

 public void getContent(Message msg)
 {
 try
 {
 String contentType = msg.getContentType();
 System.out.println("Content Type : " + contentType);
 Multipart mp = (Multipart) msg.getContent();
 int count = mp.getCount();
 for (int i = 0; i < count; i++)
 {
 dumpPart(mp.getBodyPart(i));
 }
 }
 catch (Exception ex)
 {
 System.out.println("Exception arise at get Content");
 ex.printStackTrace();
 }
 }

 public void dumpPart(Part p) throws Exception
 {
 // Dump input stream ..
 InputStream is = p.getInputStream();
 // If "is" is not already buffered, wrap a BufferedInputStream
 // around it.
 if (!(is instanceof BufferedInputStream))
 {
 is = new BufferedInputStream(is);
 }
 int c;
 System.out.println("Message : ");
 while ((c = is.read()) != -1)
 {
 System.out.write(c);
 }
 }

 public static void main(String args[])
 {
 new MailReader();
 }
}

  1. Roshan Shrestha
    March 22, 2010 at 2:50 pm

    I would recommend using Apache Camel for this, makes it really simple for handling mail events.

    • March 23, 2010 at 11:53 am

      Hi Roshan,
      Thanks for your valuable suggestion.I have look at apache mail.But when i have tried to run the code it returns the error thats like the message class missing.Can you resolve this problem?

  2. javaguru89
    April 12, 2010 at 11:15 am

    thanks buddy………

    its really help me a lotttttttttttt

    • April 12, 2010 at 12:49 pm

      Hi friend,
      Thanks for your valuable comment.

  3. Satish
    June 13, 2010 at 6:36 pm

    Thank You Very Much Sir!
    It was extremely helpful.

  4. junaid
    November 18, 2010 at 4:36 pm

    how do i run this program in java

    and i would like to knw about , how to send email to any friend

    thank you,

    Junaid

  5. November 20, 2010 at 4:02 am

    Hi Junaid,

    You have to add the mail.jar with your library for run this program.
    And i have already post a article related to sending mail,Have a look at it,

    Java code sending Mail with Attachment using Java Mail API

    • November 21, 2012 at 6:30 am

      hi
      five emai id in hard code run program serch today date and give me result.

    • November 21, 2012 at 6:35 am

      Hi ,

      I want to add 5 email ids in Hard code run program and when i enter todays date the emails received on that specific date will come out as the result.

  6. amyna
    November 26, 2010 at 9:58 am

    hi

    how to send and read email without opening the email use gmail and broadband connection using java?

    thank you.

    • November 26, 2010 at 12:14 pm

      By using this code you can receive the mail from gmail.Only thing u have to do is place your mail id and password in the code.
      And if you wants to send mail,go through this link and send the mail using this code.
      send mail using java code
      Happy coding….

  7. karthika
    March 5, 2011 at 5:31 am

    hai sir,
    i’m doing project in java titled network system communication.i need a help in watching the time allocated for the client.how to do this.any suggestions?????

  8. Muhammad Zulqarnain
    May 1, 2011 at 5:09 am

    Hello sir,
    How can i fetch message date from live ??? I use pop3 server to fetch emails and port 995.

  9. billy
    June 6, 2011 at 7:40 am

    hi,
    how to read email without opening it with broadband connection using netbeans?

    thank u.

  10. Nguyễn Lan
    August 9, 2011 at 5:47 pm

    metoojava :
    By using this code you can receive the mail from gmail.Only thing u have to do is place your mail id and password in the code.
    And if you wants to send mail,go through this link and send the mail using this code.
    send mail using java code
    Happy coding….

    Hi metoojave
    How will I have to use the methods of class above for website application. I use JSP/Servlet to code & GlassFish Server to deploy. Thanks!

  11. Neptune
    August 27, 2011 at 12:44 pm

    Need help to create new email notifier

  12. Soundar
    November 5, 2011 at 1:22 am

    Hi Harri,

    I am getting the following error.
    javax.mail.AuthenticationFailedException: [AUTHENTICATIONFAILED] Invalid credentials (Failure)
    at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:474)
    at javax.mail.Service.connect(Service.java:275)
    at javax.mail.Service.connect(Service.java:156)
    at getgmail.GetGMail.(GetGMail.java:39)
    at getgmail.GetGMail.main(GetGMail.java:25)
    Java Result: 2

    What could be the problem.

    • Narasimha
      December 28, 2012 at 10:23 am

      add mail.jar and activation.jar files

  13. mahesh
    November 10, 2011 at 11:44 am

    thanx alot its very good example

  14. AJ
    November 25, 2011 at 8:18 am

    Thank To Site “metoojava” And Developers Who Developed The Above Example………☺☺☺

  15. Namit
    December 19, 2011 at 6:29 am

    I am getting the below error: Can someone comment on this , how to resolve this issue

    javax.mail.AuthenticationFailedException: EOF on socket
    at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:146)
    at javax.mail.Service.connect(Service.java:275)
    at javax.mail.Service.connect(Service.java:156)
    at com.info.mail.MailReader.(MailReader.java:55)
    at com.info.mail.MailReader.main(MailReader.java:236)

  16. ceasar
    January 26, 2012 at 1:34 pm

    javax.mail.NoSuchProviderException: imaps
    at javax.mail.Session.getService(Session.java:784)
    at javax.mail.Session.getStore(Session.java:578)
    at javax.mail.Session.getStore(Session.java:540)
    at javax.mail.Session.getStore(Session.java:519)
    at mailReader.MailReader.(MailReader.java:21)
    at mailReader.MailReader.main(MailReader.java:142)

    i am getting this error while running the above codes.
    please help me..
    thanks in advance!

    • Nilaxi
      February 3, 2012 at 4:29 am

      Which code you have used?????

  17. Nilaxi
    February 3, 2012 at 4:28 am

    Hi… i need ascript which fetch my old mails with their attachment and forward it….. Please help me out……

  18. Parth Doshi
    April 6, 2012 at 6:37 am

    Thanks for the code…I am not getting the content of the mails…Please help me…

    • April 8, 2012 at 7:24 am

      Please post the code which you used.It ll helpful to found the solution.

  19. July 15, 2012 at 10:39 am

    hi…thax for the code.do we have to athenticate user using AOUTH protocol before getting his\her email…

  20. Aman Sharma
    October 13, 2012 at 10:25 am

    thanx for the code it helps me a lot

  21. Narasimha
    December 28, 2012 at 10:20 am

    Thank you every much…..
    But how can I display top 10 emails which are both read and unread emails

  22. Manuel
    February 1, 2013 at 2:58 pm

    works great!… thanks!
    But what if an email has attached files? how can recognize that?, how can i download those files?

    thanks

  23. February 20, 2013 at 4:39 am

    You truly created several terrific stuff throughout your blog, “Java Code to Receive Mail using JavaMailAPI Metoojava’s Blog”. I’ll become coming back
    again to ur web site in the near future. With thanks ,Hilario

  24. Mahesh
    December 25, 2013 at 7:18 am

    How can i access microsoft access server mails.

  25. Mahesh
    December 25, 2013 at 7:19 am

    how can i access the microsoft outlook server mails in my java code.

  1. March 21, 2010 at 4:40 pm
  2. March 21, 2010 at 4:40 pm

Leave a comment