Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javamail api to access gmail inbox messages

I have been trying to use the javamail api to read gmail inbox messages. I found the following code on the internet. I'm trying to run this on Eclipse, but it is failing with an "Invalid credentials exception". I have mail.jar, activation.jar, imap.jar and other jar files in the lib directory of the web-app.

Any ideas as to why I am receiving this exception ? Thanks.

javax.mail.AuthenticationFailedException: Invalid credentials n67if632335wep.219
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)


package org.mb.mail;

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;
import javax.mail.*;

public class MailReader {

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);
        }

    }

}
like image 578
prashanth T Avatar asked Jan 26 '26 14:01

prashanth T


1 Answers

Throw away that code and use this code from the JavaMail FAQ, where you'll also find lots of other helpful tips, including debugging tips.

like image 178
Bill Shannon Avatar answered Jan 29 '26 03:01

Bill Shannon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!