Sunday, September 27, 2015

Get Inbox Email

Kali ini saya akan membuat bagaimana cara mengambil list inbox yang ada pada email. Metode pengambilan email kali ini menggunakan protokol POP3, singkatnya kita membuat email client kita sendiri. untuk lebih jelasnya tentang protocol pop3 cek google mail atau di wiki.

Kita cukup membuat 1 class java saja.

1. CheckingMails

CheckingMails.java

import java.util.Properties;
import javax.mail.Address;
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 CheckingMails {

    public static void check(String host, String storeType, String user, String password) {
        try {
            Properties properties = new Properties();
            properties.put("mail.pop3.host", host);
            properties.put("mail.pop3.port", "995");
            properties.put("mail.pop3.starttls.enable", "true");
            Session emailSession = Session.getDefaultInstance(properties);

            Store store = emailSession.getStore("pop3s");

            store.connect(host, user, password);

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

            Message[] messages = inbox.getMessages();
            System.out.println("Message all : " + messages.length);

            for (int i = 0; i < messages.length; i++) {
                Message message = messages[i];
                System.out.println("---------------------------------");
                System.out.println("Email Number : " + (i + 1));
                System.out.println("Time : " + message.getSentDate());
                System.out.println("Subject : " + message.getSubject());
                System.out.println("From: " + message.getFrom()[0]);

            }
            inbox.close(false);
            store.close();

        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
      String host = "pop.gmail.com";//server mail
      String mailStoreType = "pop3";
      String username = "yourmail@mail.com";
      String password = "your password mail";

      check(host, mailStoreType, username, password);
    }
}
Output :
 

No comments:

Post a Comment