Access GMail with imap using java mail api

24 01 2009

I had to search through quite a few web pages for this. So I am putting it here for future reference. My conscience pricks for putting all the code in main method. But I guess this is an exception. :)

import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

public class InboxReader {

public static void main(String args[]) {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "<username>", "password");
System.out.println(store);

Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
Message messages[] = inbox.getMessages();
for(Message message:messages) {
System.out.println(message);
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}

}

}

UPDATE: Below update is from the Niteesh Bhargava’s comment. Thanks Niteesh.

Above code won’t work always :

Folder outbox = store.getFolder(”[Gmail]/Sent Mail”);

Reason :-
, because Gmail server doesn’t create folders in English always , i.e. if your profile is in French or Hindi your gmail folders names will be different.

Solution :-
Use the code below to get the available gmail folders for your account

Folder[] folder = store.getDefaultFolder().list(); // get the array folders in server
int i=0;
for( i=0;i<folder.length;i++)
System.out.println("Press "+i+" to read "+folder[i].getName()+" folder");
int choice=in.nextInt(); // getName() method returns the name of folder

About these ads

Actions

Information

84 responses

16 02 2009
Sandeep Arneja

thank you sir

16 02 2009
Sandeep Arneja

Make the following change to fetch ONLY UNREAD messages:

//Message messages[] = inbox.getMessages();

FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);

Message messages[] = inbox.search(ft);

12 03 2009
harikrishnan83

Thanks for your comments. :)
I would also suggest using Commons email where possible.

25 09 2012
vikasdhillon

thanx a lot sandeep…..i was searching….4 it..

16 03 2009
Murali

hi Hari..thanks for you post

16 03 2009
Murali

How to pick particular message from the inbox…

9 04 2009
mitali

hi!!!!!!!!!!!!
the data u provided had been a great help to me and i really wanna thank u for that ,but i have one doubt as u hv written that in order to get folder inbox u hv written
Folder inbox = store.getFolder(“Inbox”);
but wat if i wanna get the folder Sent Mails using IMAP by accessing gmail???????????
am writing:-
Folder outbox = store.getFolder(“Sent Mail”);
but its showing the NotFoundFolderException.
pls………… do reply

13 04 2009
harikrishnan83

Use the below code
Folder outbox = store.getFolder(”[Gmail]/Sent Mail”);

Further reading – http://www.chinhdo.com/20071216/gmail-imap-tips/

9 06 2013
Niteesh Bhargava

Hi harikrishnan83

your code won’t work always :

Folder outbox = store.getFolder(”[Gmail]/Sent Mail”);

Reason :-
, because Gmail server doesn’t create folders in English always , i.e. if your profile is in French or Hindi your gmail folders names will be different.

Solution :-
Use the code below to get the available gmail folders for your account

Folder[] folder = store.getDefaultFolder().list(); // get the array folders in server
int i=0;
for( i=0;i<folder.length;i++)
System.out.println("Press "+i+" to read "+folder[i].getName()+" folder");
int choice=in.nextInt(); // getName() method returns the name of folder
for(i=0;i<folder.length;i++)
if(choice==i){
folder[i].open(Folder.READ_ONLY);

Message[] message = folder[i].getMessages();

for (int j = 0; j < message.length; j++) {
System.out.println("———— Message " + (j + 1) + " ————");
System.out.println("SentDate : " + message[j].getSentDate());
System.out.println("From : " + message[j].getFrom()[0]);
System.out.println("Subject : " + message[j].getSubject());
System.out.print("Message : "+message[j].getContent());

}
folder[i].close(true);
}

store.close();

16 06 2013
harikrishnan83

Thanks Niteesh. I will update content as per your comments.

14 04 2009
Kapil

hi in the above code i found an javax.mail.AuthenticationFailedException: while the user name and password is correct and i already attached mail.jar and activation.jar… Please help me out as i had never work with mail API. And let me know if i can fetch the address book by mail API..

Thanks in advance
Kapil Rana

6 11 2009
Mahmoud Fouad

Same problem to me ???

8 05 2009
abdul basith m

// for all gmail message
FetchProfile fp = new FetchProfile();
Message[] messages = inbox.getMessages();
inbox.fetch(messages, fp);
for (int i = 0; i < messages.length; i++) {

System.out.println(“Subject” + messages[i].getSubject());
}

11 05 2009
abdul basith m

hi!!!!!!!!!!!!
the data u provided had been a great help to me and i really wanna thank u for that ,but i have one doubt

and i need of.. to display messages from gmail.
pls………… do reply

14 05 2009
kishore

hi
thanks
for your information the data u sented is really helpfull for me

20 05 2009
kishore

Dear sir,
Its great ur code is helping me a lot,

and i need a small requirement,

here first we are counting the messages and then getting dates,

and what i need is based on todays date i want to count the messages.

Please help me regarding this sir,

Thanku..

21 05 2009
Mike

Hi, Thanks for the help! Your code is awesome!! My code has to constantly log off and log in back to gmail, and it gives me a Web Login Failure error. It seems to be a common problem but I am unable to determine a fix for it by using the above code. Could you please let me know if you can get a workaround to this.

7 06 2009
harikrishnan83

Can you please post your code here, so that it is easier for me to reproduce this problem.

5 06 2009
maroe

hi..
i wanna get messages from a label, for example LabelA,
i’ve written: Folder inbox = store.getFolder(“[Gmail]\LabelA”);
but it’s showing: javax.mail.FolderNotFoundException: [Gmail]/LabelA not found

need a help..
thanks :)

29 06 2009
Alexander

Hi maroe,

this is simple. Just change one line and you ‘ll be fine:

Change
Folder inbox = store.getFolder(”[Gmail]\LabelA”);
to
Folder inbox = store.getFolder(”LabelA”);

So long,

Alexander

7 09 2009
harikrishnan83

Thanks Alexander.

Cheers,
HariKrishnan

7 06 2009
kris

hi!
The code was of great help.But i am trying to retrieve only the new mails using imap. Using the SEEN flag will cause even the older mail marked as unread(by the user) to appear in the results.Could u suggest a way to get around this problem??

30 06 2009
Alexander

Hi all,

does anybody know how I can get a list of labels. I have tried
Folder folder = store.getFolder(“Inbox”);
folder.open(Folder.READ_ONLY);
Folder[] fs = folder.list(); // returns an empty Array
and

Folder[] fs = folder.listSubscribed();
does the same thing.

When I connect using Apple Mail, all labels are converted to folders. All emails are found in the inbox, but I need to have a kind of structure.

So help me please to answer the question, how can I get a list of it, to write a generic application without knowing the labels?

Cheers Alexander

3 08 2009
Karthik

Thanks for the nice utility. Is it possible to search through the messages with RegEx expressions?

12 08 2009
Sheshankit

I use this code ,but it is not working.
Error comes as
javax.mail.MessagingException: Network is unreachable: connect;
nested exception is:
java.net.SocketException: Network is unreachable: connect
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:145)
at javax.mail.Service.connect(Service.java:227)
at javax.mail.Service.connect(Service.java:131)
at com.InboxReader.main(InboxReader.java:29)

7 09 2009
anshul

hi hari
i wish to access gmail content such as mails,contact book specific to a user.can you please help me with that.
I wish to use either java or .net.Please tell me possible options in both

7 09 2009
harikrishnan83

Hey Anshul,

Can you give me a little more detail about your requirement. Both java and C# have equally good apis to read and write emails. I would be able to tell you the advantages of specific approaches if you send me more details.

Cheers,
HariKrishnan

9 09 2009
anshul

hi hari
as i told you earlier. i wish to create an application that allows me to access contents of gmail specific to a user which i could save on my local machine (either in a database or in form of a file).For eg: i woud create an application and user would provide me his email id and password.Using his id and password application would log into his account and extract his emails, the content within his mails,his contacts etc.
It would be a windows application and would run on windows.

i do not require any api previously built i wish to create it myself.so i wish to know the way to create it.Are any libraries or classes available in \.net or java to suffice my work.

I know that to do so i would have to implement imap/pop3 protocol. but dont know how to do so.

What else information do you require?Can you please specify it?
Thank you

9 09 2009
harikrishnan83

This is should be very simple. My preference would be to use javax.mail api (http://java.sun.com/products/javamail/). It is very simple to learn and use. The code to access the mail account should be as simple as the example shown in my post.

Before all this, please remember that the person submitting his username and password to your application should have enabled imap access on gmail.

let me know if this answers your question.

Cheers,
HariKrishnan

20 09 2009
anshul

hi hari
thanks for reply.
I am a bit new to java have mainly worked on core java.
I wanted to know how to run this code if i were using netbeans.Moreover do i need a server for this purpose(like tomcat,glassfish). Do i need to create a servelet for this purpose.

Moreover what all data can i access from gmail.
thanking you

4 02 2010
harikrishnan83

hey there

a very late reply, better late than never
you dont need any particular ide like netbeans to run this. All you need is standard jdk and java mail jar.

remember to enable imap on the mail account

28 09 2009
anshul

hi hari
i am using javamail api.i wanted to know how to access contents of mail & senders email address?

thanks in advance

1 11 2010
Rohit

you can access contents of mail by using this……

if(msg.getContentType().toLowerCase().contains(“text/plain”)){
String content=(String)msg.getContent();
s.o.p(content);
}

else if(msg.getContentType().toLowerCase().contains(“text/html”)){
String content=(String)msg.getContent();
editorPane.setText(content);
}

else{
InputStream is=(String)msg.getInputStream();
//read bytes from inputstream
}

5 10 2009
boyz

public static void content(Part p) throws Exception
{

// for (Enumeration s = p.getAllHeaders(); s.hasMoreElements(); )
// {
// System.out.println(s.nextElement());
//
// }

String ct=p.getContentType();
System.out.println(ct);
if(p.isMimeType(“text/plain”) && !p.isMimeType(“text/html”))
{
System.out.println(p.getContent().toString());
}
else if(p.isMimeType(“Multipart/*”))
{
Multipart obj=(Multipart)p.getContent();
int count=obj.getCount();
//System.out.println(count);

// BodyPart bp;
for(int j=0;j<count;j++)
{

// bp=obj.getBodyPart(j);

content(obj.getBodyPart(j));

}

} else if (p.isMimeType("message/rfc822"))
{
content((Part)p.getContent());
}
else if(p.isMimeType("text/html"))
{
Object s=p.getContent();
if(s instanceof String)
{
System.out.println("This is a string");
System.out.println((String)s);
}
}
else
{
if (true) {
/*
* If we actually want to see the data, and it's not a
* MIME type we know, fetch it and check its Java type.
*/
Object o = p.getContent();
if (o instanceof String) {
System.out.println("This is a string");
//pr("—————————");
System.out.println((String)o);
}
else
System.out.println("unknown type");
}
}
}

EG oF THE OUTPUT:

TEXT/HTML; charset=UTF-8
This is a string

FacebookfacebookHi Anshul,Anurag Gupta added you as a friend on Facebook. We need to confirm that you know Anurag in order for you to be friends on Facebook. 

CAn u please tell me how to display data without using these tags ie only text gets displayed and not the HTML tags with it.Thanks in advance.

Please reply soon its urgent

23 10 2009
info

Hey thanks. This post is very helpful. Thanks a lot.

8 12 2009
Subho

inbox count which is returned by your code is not matching with the actual count which gets displayed gmail.

Please help.

4 02 2010
harikrishnan83

sorry for the reply, I sometimes miss comments, I think my code is referring to unread mails only
Try to see if you can actually get a count irrespective of whether the mails are read or unread.

14 01 2010
Anoop

Sir,
How can i get contents (Body) of a mail in readable string format using java mail api.

please give me a solution

29 01 2010
Hans

Can I use imap protocol with the java mail api to get pushed messages from gmail? Polling for messages is no option.

31 01 2010
harikrishnan83

Not sure if you are referring to p-imap, I did some searching and have realized gmail does not support push IMAP. Correct me if I am wrong. I will try this out and let you know. Thanks for the comment.

Cheers,
HariKrishnan

1 02 2010
Hans

I couldn’t test it yet but I found that gmail supports imap idle (not p-imap indeed). According to the API there is the idle() method of the IMAPFolder (http://java.sun.com/products/javamail/javadocs/com/sun/mail/imap/IMAPFolder.html#idle%28%29). Only not sure on how to use. I think the addMessageCountListener(MessageCountListener l) will be spawned!?

1 02 2010
harikrishnan83

Hey Hans,

I did manage to run a small test, but nowhere close to good code. If you can live with this for now. I am working on a better abstraction.


Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "", "");
IMAPFolder inbox = (IMAPFolder) store.getFolder("Inbox");
inbox.addMessageCountListener(new MessageCountListener() {
public void messagesAdded(MessageCountEvent messageCountEvent) {
Message[] messages = messageCountEvent.getMessages();
for (Message message : messages) {
System.out.println(message);
}
}
public void messagesRemoved(MessageCountEvent arg0) {
}
});
inbox.open(Folder.READ_ONLY);
inbox.idle();
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}

2 02 2010
Carlos

Hi,

Thanks for your code and explanations. Do you know if there is any way to find out what is the URL of the message?

Thanks,

4 02 2010
harikrishnan83

sorry, not sure I know a way, may I know how a message URL would help you

5 02 2010
Carlos

Just I want to read the message in the browser as I usually do with my gmail messages. This way I can avoid writing an email content visualizer and deal with DataHandlers wich is a class I am not familiar with; I might be required to develop with JDK 1.5.

4 02 2010
kk shashi

Nice Tutorial . It is very useful .
Thanks

4 02 2010
harikrishnan83

thanks for the comment

23 02 2010
Peter

Hi,

Thanks for the sample code for reading emails form gmail account.
I would like to know how to apply a label for the read message(s) programatically.

Could you please let me know how to do that using the API?

Thanks in advance,
Peter.

24 02 2010
harikrishnan83

To the best of my knowledge, label is an imap Flag. you can set and read imap Flags using javax.mail.Flags.Flag.

http://java.sun.com/products/javamail/javadocs/javax/mail/Flags.Flag.html

I have not tried it out
let me know if this helps :)

24 02 2010
Peter

Hi,

Thanks for the reply. I am using the setFlag(Flags.Flag.ANSWERED, true) method to mark a given message as read. I would like to know if they is a way to apply the custom label (like google label) so that messages could be marked with its own label.

Thanks again,
Peter.

6 03 2010
ealif

thanks :) very helpful.

12 05 2010
Chinmay Soman

This was very helpful. Especially to put together a quick Reader.

Thanks a lot

12 05 2010
harikrishnan83

Glad that you found it useful :)

10 07 2010
digislayer

Hey Harikrishnan, That’s a really wonderful code!

I’m new to this API, and never before used Java with any form of networking. Currently, I need a code that can respond whenever a new email arrives on a given email address(Gmail). It then has to retrieve the subject of the received mail and store it to a string value. Can you help me out?

10 07 2010
digislayer

And yes, the code has to continuosly keep monitoring for any new mail’s arrival, and react in the above way every time a new mail arrives..the same string variable can be over-written with the new subject string any number of times…

Any help would be greatly appreciated as I’m currently working on a project that depends on this. Kind of urgent! :(

10 07 2010
harikrishnan83

Once you get hold of the inbox or any other folder you are interested in you can add a MessageCountListener to it. Every time when a new message is added or removed you get a notification.

Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);

inbox.addMessageCountListener(new MessageCountListener() {

@Override
public void messagesAdded(MessageCountEvent arg0) {
System.out.println("Messages added");
}

@Override
public void messagesRemoved(MessageCountEvent arg0) {
System.out.println("Messages removed");
}

});

10 07 2010
digislayer

Thanks a lot!

But, how do I copy the “subject” string of ONLY the new mail into a string value? Basically, my project involves updating of a string variable everytime a new mail arrives, with the subject field of the newest mail copied to the subject string. I’m not understanding how to work on a particular mail. How do we point to a particular mail only?

10 07 2010
harikrishnan83

You should be able to get hold of the messages from the event listener. Take a look at the api for Message. Looks like you can get the subject out of the message. http://java.sun.com/products/javamail/javadocs/com/sun/mail/imap/IMAPMessage.html#getSubject%28%29. The api is not so intuitive, but you can read the docs to understand it.

1 11 2010
Rohit

hy, does anybody know how to get address book from gmail account?

12 11 2010
Xile

The javax.mail.* package is not part of the standard Java SDK – I have tried creating a Java EE project (in Netbeans) hoping that the packages may be in Java EE – however, no luck. Could any one explain how to get a hold of, og simply import these packages?

12 11 2010
harikrishnan83

Use the java mail api jar. You can download it here.

http://www.oracle.com/technetwork/java/index-138643.html

23 12 2010
Peter

Thanks for the great mini-tutorial, awesome work and it made my life a lot easier.

30 06 2011
Saisudhakar Amuru

Hi hari,
great information you have kept.
But unfortunately i am getting following exception while running above program.
javax.mail.NoSuchProviderException: No provider for imaps

when i came into debug more, below line was throwing exception
Store store = session.getStore(“imaps”);

please send us the working code, and send the right inputs.

Thanks,
Sai

2 07 2011
harikrishnan83

Thanks for your comment. This exception usually means there may be a problem with your mail-.jar. Would not be able to help you more without info like your classpath and mail jar version.

7 07 2011
PPK

this has been very helpful to primarily understand how the imap mailer works.
thanks for sharing the code.

28 07 2011
Ravikumar maddi

Hi Hari,
Good effort, Thanks,
I want to mark as read for complete folder or single message. How can we do ?
Thanks,
Ravi M

21 09 2011
Amol

Hi Hari,

I’m getting following error while trtying to connect to IMAP server.

javax.mail.MessagingException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target;

I have set following properties
fMailServerConfig.setProperty(“mail.store.protocol”, “imap”);
fMailServerConfig.setProperty(“mail.imap.host”,smtp_Host);
fMailServerConfig.setProperty(“mail.debug”, “true”);
fMailServerConfig.setProperty(“mail.imap.port”, “993”);
fMailServerConfig.setProperty(“mail.imap.socketFactory.port”, “993”);
fMailServerConfig.setProperty(“mail.imap.host”, smtp_Host);
fMailServerConfig.setProperty(“mail.imap.socketFactory.class”, “javax.net.ssl.SSLSocketFactory”);
fMailServerConfig.setProperty(“mail.imap.socketFactory.fallback”, “false”);

What I have understood by this error is that this is a certificate issue. But unable to find solution for the same.

Could you please help me on this

5 10 2011
harikrishnan83

Looks like you have to add imap server’s certificate to your trusted cert store
1. Download imap server’s certificate
2. Locate your cacerts file
3. Use keytool to import the certificate to your cacerts file

18 01 2012
sandesh

Caused by: java.net.ConnectException: Connection timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:337)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:198)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:612)
at sun.security.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:160)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:288)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231)
at com.sun.mail.pop3.Protocol.(Protocol.java:107)
at com.sun.mail.pop3.POP3Store.getPort(POP3Store.java:261)
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:206)
… 32 more

18 01 2012
harikrishnan83

Have you checked if your mail server is reachable from your production server?

6 02 2012
Erwin Burgos Gano

thanks to all… its big help for me

20 03 2012
http://mensengagementrings.ca

But wanna comment that you have a very nice site, I enjoy the design it really stands out.

26 03 2012
mishty

plz let me knw how to get the body of mail..

5 04 2012
Chux Uzoeto

What if one wanted to send out email from the java app/code using imap (instead of smtp), how would one go about this? ..

I find using imap for sending out emails like this more attractive, because the sent folder would automatically hold the sent message in the Sent folder .. but even if this is not automatic, the code can be extended to copy all sent mails to the Sent folder.

11 07 2012
raghu

javax.mail.AuthenticationFailedException: Invalid credentials f55if399401wed.93
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:665)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at org.mb.mail.MailReader.main(MailReader.java:23)

I been getting above exception when i run the code ? – the credentials are correct.

24 01 2013
Ankit Singla

hello sir i have tried this code but i am getting this error:

javax.mail.NoSuchProviderException: Unable to locate provider for protocol: imaps
at javax.mail.Session.getProvider(Session.java:229)
at javax.mail.Session.getStore(Session.java:270)

my code is same as yours.

2 06 2013
Meghna

Thanks for such a good explanation.. Even this http://www.compiletimeerror.com/2013/06/reading-email-using-javamail-api-example.html might help… have a look…

4 06 2013
Rajendra Verma

I am using the same code in android. While accessing Multipart getcontent() method I get error like DataHandler class is missing. Please help me by your precious suggestion. Thanks in advance

4 06 2013
6 09 2013
chetankhatritan

I am Having Error in Windows 7 only not in windows XP ,Error is
javax.mail.MessagingException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target;
nested exception is:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:670)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at inboxreader.InboxReader.main(InboxReader.java:27)
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1886)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1341)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:153)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:804)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1016)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
at com.sun.mail.util.SocketFetcher.configureSSLSocket(SocketFetcher.java:548)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:352)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:233)
at com.sun.mail.iap.Protocol.(Protocol.java:113)
at com.sun.mail.imap.protocol.IMAPProtocol.(IMAPProtocol.java:111)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:637)
… 3 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1323)
… 16 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)

———————————————————————————————
————————–Source Code is below————————————

import java.io.IOException;
import java.util.Properties;
import javax.mail.*;
import javax.mail.search.*;

public class InboxReader
{
public static void main(String s[])
{
Properties pros=System.getProperties();
try
{
Session session=Session.getDefaultInstance(pros,null);
Store store=session.getStore(“imaps”);
store.connect(“imap.gmail.com”,”email@gmail.com”,”password”);

Folder inbox=store.getFolder(“INBOX”);
inbox.open(Folder.READ_ONLY);
FlagTerm ft=new FlagTerm(new Flags(Flags.Flag.SEEN),true);
Message message[]=inbox.search(ft);
for(int i=0;i<=message.length-1;i++)
{
System.out.println((i+1)+":"+message[i].getSubject()+"\n");

}

}
catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
}
catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
}

}

}

19 10 2013
mambu

Hi, very nice code! and it’s what i have to find:)
but one things, if i can ask i have to read only the “not read” mail, how i can do this, with your code i read all INBOX mail and it order the mail from the first one(very old mail)
sorry if my english is bad and thank you if you con help me:)

Bye
Manuel

20 10 2013
mambu

i’ve read the first comment but for now daesn’t work…i continue to try;)

20 10 2013
harikrishnan83

Hi Manuel,

You can use SearchTerm to filter the unseen messages.
Instead of directly calling inbox.getMessages, use below code.

SearchTerm unreadEmails = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
Message messages[] = inbox.search(unreadEmails);

Thanks and Regards,
HariKrishnan

20 10 2013
mambu

thanks, i’ve done it a few minute ago!;) thank you and good job

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




Follow

Get every new post delivered to your Inbox.

Join 239 other followers

%d bloggers like this: