Advertisement
Guest User

JavaMail

a guest
Oct 15th, 2017
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.15 KB | None | 0 0
  1. package com.company;
  2.  
  3. import java.io.IOException;
  4. import java.util.Properties;
  5. import javax.mail.*;
  6.  
  7.  
  8. public class Main{
  9.  
  10.     public static void receiveEmail(String pop3Host, String storeType,
  11.                                     String user, String password) {
  12.         try {
  13.             //1) get the session object
  14.             Properties properties = new Properties();
  15.             properties.put("mail.imap.host", "imap.gmail.com");
  16.             properties.put("mail.imap.port", "993");
  17.             properties.put("mail.imap.ssl.enable", "true");
  18.  
  19.             Session emailSession = Session.getInstance(properties);
  20.  
  21.             Store emailStore = emailSession.getStore("imaps");
  22.             emailStore.connect(pop3Host,993,user, password);
  23.  
  24.  
  25.  
  26.             //3) create the folder object and open it
  27.             Folder emailFolder = emailStore.getFolder("INBOX");
  28.             emailFolder.open(Folder.READ_ONLY);
  29.  
  30.             //4) retrieve the messages from the folder in an array and print it
  31.             Message[] messages = emailFolder.getMessages();
  32.             for (int i = 0; i < messages.length; i++) {
  33.                 Message message = messages[i];
  34.                 System.out.println("---------------------------------");
  35.                 System.out.println("Email Number " + (i + 1));
  36.                 System.out.println("Subject: " + message.getSubject());
  37.                 System.out.println("From: " + message.getFrom()[0]);
  38.                 System.out.println("Text: " + message.getContent().toString());
  39.             }
  40.  
  41.             //5) close the store and folder objects
  42.             emailFolder.close(false);
  43.             emailStore.close();
  44.  
  45.         } catch (NoSuchProviderException e) {e.printStackTrace();}
  46.         catch (MessagingException e) {e.printStackTrace();}
  47.         catch (IOException e) {e.printStackTrace();}
  48.     }
  49.  
  50.     public static void main(String[] args) {
  51.  
  52.         String host = "imap.gmail.com";//change accordingly
  53.         String mailStoreType = "pop3s";
  54.         String username= "****";
  55.         String password= "****";//change accordingly
  56.  
  57.         receiveEmail(host, mailStoreType, username, password);
  58.  
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement