Java Email Folder receive email with Authenticator

Description

Java Email Folder receive email with Authenticator

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;

public class Main {
   public static void main(String[] args) throws Exception {

      String host = "pop.gmail.com", protocol = "pop3s";
      String username = "usr.some", password = "some.usr";

      Properties props = new Properties();
      // provide host
      props.put("mail." + protocol + ".host", host);

      // provide user and password
      Authenticator auth = new Authenticator() {
         public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
         }//from   www.j av  a  2 s .  com
      };
      Session session = Session.getInstance(props, auth);
      Store store = session.getStore(protocol);
      store.connect();

      session.setDebug(true);
      store.connect(host, username, password);
      Folder inbox = store.getFolder("Inbox");
      if (inbox.exists()) {
         inbox.open(Folder.READ_ONLY);
         Message[] emails = inbox.getMessages();
         for (int i = 0; i < emails.length; i++) {
            System.out.println("Message " + (i + 1));
            emails[i].writeTo(System.out);
         }
         inbox.close(false);
      } else
         System.out.println("Inbox not available");
      store.close();
   }
}



PreviousNext

Related