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(); } }
Leave a comment Cancel reply
Categories
- 1 (1)
- ie (1)
- ie fix (1)
- ie issues (1)
- Java (8)
- Java 7 (2)
- Mail ID validation (1)
- Regular Expression (1)
- mail (2)
- receivemail (1)
- Spring (2)
I would recommend using Apache Camel for this, makes it really simple for handling mail events.
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?
thanks buddy………
its really help me a lotttttttttttt
Hi friend,
Thanks for your valuable comment.
Thank You Very Much Sir!
It was extremely helpful.
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
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,
hi
five emai id in hard code run program serch today date and give me result.
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.
hi
how to send and read email without opening the email use gmail and broadband connection using java?
thank you.
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….
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?????
Hello sir,
How can i fetch message date from live ??? I use pop3 server to fetch emails and port 995.
hi,
how to read email without opening it with broadband connection using netbeans?
thank u.
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!
Need help to create new email notifier
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.
add mail.jar and activation.jar files
thanx alot its very good example
Thank To Site “metoojava” And Developers Who Developed The Above Example………☺☺☺
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)
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!
Which code you have used?????
Hi… i need ascript which fetch my old mails with their attachment and forward it….. Please help me out……
Thanks for the code…I am not getting the content of the mails…Please help me…
Please post the code which you used.It ll helpful to found the solution.
hi…thax for the code.do we have to athenticate user using AOUTH protocol before getting his\her email…
thanx for the code it helps me a lot
…
Thank you every much…..
But how can I display top 10 emails which are both read and unread emails
works great!… thanks!
But what if an email has attached files? how can recognize that?, how can i download those files?
thanks
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
How can i access microsoft access server mails.
how can i access the microsoft outlook server mails in my java code.