Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- import java.util.Properties;
- import javax.mail.FetchProfile;
- 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 MailReader {
- public static void main(String[] args) {
- String host = "pop.gmail.com";// change accordingly
- String mailStoreType = "pop3";
- String username = "";// change accordingly
- String password = "";// change accordingly
- check(host, mailStoreType, username, password);
- }
- public static void check(String host, String storeType, String user, String password) {
- try {
- // create properties field
- 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);
- // create the POP3 store object and connect with the pop server
- Store store = emailSession.getStore("pop3s");
- store.connect(host, user, password);
- // create the folder object and open it
- Folder emailFolder = store.getFolder("INBOX");
- emailFolder.open(Folder.READ_ONLY);
- // retrieve the messages from the folder in an array and print it
- //Message[] messages = emailFolder.getMessages();
- Message[] messages = emailFolder.getMessages();
- FetchProfile fp = new FetchProfile();
- fp.add(FetchProfile.Item.ENVELOPE);
- emailFolder.fetch(messages, fp);
- //messages = emailFolder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
- // Sort messages from recent to oldest
- Arrays.sort( messages, ( m1, m2 ) -> {
- try {
- return m2.getSentDate().compareTo( m1.getSentDate() );
- } catch ( MessagingException e ) {
- throw new RuntimeException( e );
- }
- } );
- for ( Message message : messages ) {
- System.out.println(
- "sendDate: " + message.getSentDate()
- + " subject:" + message.getSubject() );
- }
- /*for (int i = 0, n = messages.length; i < n; i++) {
- Message message = messages[i];
- System.out.println("---------------------------------");
- System.out.println("Email Number " + (i + 1));
- System.out.println("Subject: " + message.getSubject());
- System.out.println("From: " + message.getFrom()[0]);
- System.out.println("Text: " + message.getContent().toString());
- }*/
- // close the store and folder objects
- emailFolder.close(false);
- store.close();
- } catch (NoSuchProviderException e) {
- e.printStackTrace();
- } catch (MessagingException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
Add Comment
Please, Sign In to add comment