We already discussed the fundamentals of Java Mail API. We discussed the way by which Java Mail API is using SMTP to send emails with attachments and without any attachments. In the just previous post we discussed how POP is using to read emails from Gmail inbox.In this chapter we are discussing how IMAP is using to read emails from Gmail account.
POP vs IMAP
POP is the Post Office Protocol.IMAP is the Internet Message Access Protocol.Both are protocols using to retrieve emails from email servers.If we use POP for accessing mails from mail servers, then two way synchronization cannot be achieved.IMAP gives two way synchronization, that means , if we read mail using IMAP then the mail is mapped as read mail in mail server.If we open the mail from anywhere , then the mail will be shown as read.
Reading email in Java using IMAP
Now we are looking into an example.Here we are looking how Java Mail API is using to read unread mails from mail server.Here IMAP is using as protocol.We are accessing recent unread mails from Gmail.So IMAP should be enabled for the corresponding email account.The procedure to enable/disable IMAP/POP is explained in Google page.Put the following class in a dynamic web project.If we need to access mails from J2SE application , then we can download Java Mail API from here.Extract the zip file and include the jar files in the project path.
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Flags.Flag;
import javax.mail.search.FlagTerm;
public class ReadMailSample {
Properties properties = null;
private Session session = null;
private Store store = null;
private Folder inbox = null;
private String userName = "";// provide user name
private String password = "";// provide password
public ReadMailSample() {
}
public void readMails() {
properties = new Properties();
properties.setProperty("mail.host", "imap.gmail.com");
properties.setProperty("mail.port", "995");
properties.setProperty("mail.transport.protocol", "imaps");
session = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
try {
store = session.getStore("imaps");
store.connect();
inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.search(new FlagTerm(
new Flags(Flag.SEEN), false));
;
System.out.println("Number of mails = " + messages.length);
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
Address[] from = message.getFrom();
System.out.println("-------------------------------");
System.out.println("Date : " + message.getSentDate());
System.out.println("From : " + from[0]);
System.out.println("Subject: " + message.getSubject());
System.out.println("Content :");
processMessageBody(message);
System.out.println("--------------------------------");
}
inbox.close(true);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
public void processMessageBody(Message message) {
try {
Object content = message.getContent();
// check for string
// then check for multipart
if (content instanceof String) {
System.out.println(content);
} else if (content instanceof Multipart) {
Multipart multiPart = (Multipart) content;
procesMultiPart(multiPart);
} else if (content instanceof InputStream) {
InputStream inStream = (InputStream) content;
int ch;
while ((ch = inStream.read()) != -1) {
System.out.write(ch);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
public void procesMultiPart(Multipart content) {
try {
int multiPartCount = content.getCount();
for (int i = 0; i < multiPartCount; i++) {
BodyPart bodyPart = content.getBodyPart(i);
Object o;
o = bodyPart.getContent();
if (o instanceof String) {
System.out.println(o);
} else if (o instanceof Multipart) {
procesMultiPart((Multipart) o);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ReadMailSample sample = new ReadMailSample();
sample.readMails();
}
}
The search is for the unread mails from the inbox. The content of each mail will be displayed.
Output
Before compiling and running the class , username and password should be provided.Then compile and run the code . The unread mails will be displayed.
See Related Posts
SMTP
Sending mails from Gmail account using SMTP
Sending mails with attachment from Gmail account using SMTP
POP
THANKS!!
Thankful for this tutorial.
can you please send me how to retrieve messages from gmail or, other, by using android and how to retrieve inbox , sent items, draft messages in android coding??
no me resultó :/
I have this error message if i run this tutorial with my login
javax.mail.MessagingException: Remote host closed connection during handshake;
nested exception is:
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:726)
at javax.mail.Service.connect(Service.java:386)
at javax.mail.Service.connect(Service.java:245)
at javax.mail.Service.connect(Service.java:194)
at sk.dcore.mail.ReadMailSample.readMails(ReadMailSample.java:46)
at sk.dcore.mail.ReadMailSample.main(ReadMailSample.java:124)
Caused by: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:543)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:348)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:236)
at com.sun.mail.iap.Protocol.(Protocol.java:117)
at com.sun.mail.imap.protocol.IMAPProtocol.(IMAPProtocol.java:121)
at com.sun.mail.imap.IMAPStore.newIMAPProtocol(IMAPStore.java:746)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:689)
… 5 more
Hi ,
With the same code,even though my Inbox contains 4 emails, the inbox.getmessagecount() method is giving ‘0’ value.
Please help in this regard.Very urgent.
Connection Time out Exception ….. Please provide solution for this
javax.mail.AuthenticationFailedException: [ALERT] Invalid credentials (Failure)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:661)
at javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at other.ReadMail.readMails(ReadMail.java:47)
at other.ReadMail.main(ReadMail.java:105)
Seems a credential issue