Receive email using POP3

POP3 supports simple download-and-delete requirements for access to remote mailboxes.

Java Mail comes with Provider implementations for POP3 and IMAP, and the secure versions of those as POP3S and IMAPS.

This Howto connects to a server using the POP3S (Secure, encrypted POP3) to download messages with or without attachments and save them into files.

import java.io.*;
import java.util.*;
import javax.mail.*;

import javax.mail.internet.MimeBodyPart;

public class ReceiveMailPOP3 {
  private static final String HOST = "pop.gmail.com";
  private static final String USERNAME = "myemail@gmail.com";
  private static final String PASSWORD = "******";

  public static void doit() throws MessagingException, IOException {
    Folder folder = null;
    Store store = null;
    try {
      Properties props = new Properties();
      props.put("mail.store.protocol", "pop3s"); // Google uses POP3S not POP3
      Session session = Session.getDefaultInstance(props);
      // session.setDebug(true);
      store = session.getStore();
      store.connect(HOST, USERNAME, PASSWORD);
      folder = store.getDefaultFolder().getFolder("INBOX");
      folder.open(Folder.READ_ONLY);
      Message[] messages = folder.getMessages();
      System.out.println("No of Messages : " + folder.getMessageCount());
      System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
      for (int i=0; i < messages.length; ++i) {
        System.out.println("MESSAGE #" + (i + 1) + ":");
        Message msg = messages[i];
        String from = "unknown";
        if (msg.getReplyTo().length >= 1) {
          from = msg.getReplyTo()[0].toString();
        }
        else if (msg.getFrom().length >= 1) {
          from = msg.getFrom()[0].toString();
        }
        String subject = msg.getSubject();
        System.out.println("Saving ... " + subject +" " + from);
        // you may want to replace the spaces with "_"
        // the files will be saved into the TEMP directory
        String filename = "c:/temp/" +  subject;
        saveParts(msg.getContent(), filename);
      }
    }
    finally {
      if (folder != null) { folder.close(true); }
      if (store != null) { store.close(); }
    }
  }

  public static void saveParts(Object content, String filename)
  throws IOException, MessagingException
  {
    OutputStream out = null;
    InputStream in = null;
    try {
      if (content instanceof Multipart) {
        Multipart multi = ((Multipart)content);
        int parts = multi.getCount();
        for (int j=0; j < parts; ++j) {
          MimeBodyPart part = (MimeBodyPart)multi.getBodyPart(j);
          if (part.getContent() instanceof Multipart) {
            // part-within-a-part, do some recursion...
            saveParts(part.getContent(), filename);
          }
          else {
            String extension = "";
            if (part.isMimeType("text/html")) {
              extension = "html";
            }
            else {
              if (part.isMimeType("text/plain")) {
                extension = "txt";
              }
              else {
                //  Try to get the name of the attachment
                extension = part.getDataHandler().getName();
              }
              filename = filename + "." + extension;
              System.out.println("... " + filename);
              out = new FileOutputStream(new File(filename));
              in = part.getInputStream();
              int k;
              while ((k = in.read()) != -1) {
                out.write(k);
              }
            }
          }
        }
      }
    }
    finally {
      if (in != null) { in.close(); }
      if (out != null) { out.flush(); out.close(); }
    }
  }

  public static void main(String args[]) throws Exception {
    ReceiveMailPOP3.doit();
  }
}

Done! Happy Coding!

Related posts:

Java Program to Implement Cubic convergence 1/pi Algorithm
Các chương trình minh họa sử dụng Cấu trúc điều khiển trong Java
@Order in Spring
Jackson Exceptions – Problems and Solutions
Quick Guide to @RestClientTest in Spring Boot
Mệnh đề Switch-case trong java
Java Program to Implement Bellman-Ford Algorithm
Spring Boot - Building RESTful Web Services
Explain about URL and HTTPS protocol
Retrieve User Information in Spring Security
Java Program to Construct an Expression Tree for an Infix Expression
Rest Web service: Filter và Interceptor với Jersey 2.x (P2)
Java Program to Find kth Smallest Element by the Method of Partitioning the Array
Java Program to Implement Quick Sort Using Randomization
Rest Web service: Filter và Interceptor với Jersey 2.x (P1)
Java Program to Implement K Way Merge Algorithm
Java Program to Implement Miller Rabin Primality Test Algorithm
HttpClient Connection Management
Java Program to Perform the Sorting Using Counting Sort
Guide to CopyOnWriteArrayList
Get the workstation name or IP
Pagination and Sorting using Spring Data JPA
Java Program to Implement the Alexander Bogomolny’s UnOrdered Permutation Algorithm for Elements Fro...
Java Program to Implement WeakHashMap API
Java Program to Perform Postorder Non-Recursive Traversal of a Given Binary Tree
Java Program to Implement the Edmond’s Algorithm for Maximum Cardinality Matching
Most commonly used String methods in Java
Java Program to Find Hamiltonian Cycle in an UnWeighted Graph
Java Program to Implement Hash Tables
Spring Data JPA @Modifying Annotation
Java NIO2 Path API
JWT – Token-based Authentication trong Jersey 2.x