Get Email Message Example : Email « Network Protocol « Java

Get Email Message Example

// Fetching Mail

import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

public class GetMessageExample {
  public static void main(String args[]) throws Exception {
    if (args.length != 3) {
      System.err.println("Usage: java MailExample host username password");

    String host = args[0];
    String username = args[1];
    String password = args[2];

    // Create empty properties
    Properties props = new Properties();

    // Get session
    Session session = Session.getDefaultInstance(props, null);

    // Get the store
    Store store = session.getStore("pop3");
    store.connect(host, username, password);

    // Get folder
    Folder folder = store.getFolder("INBOX");;

    BufferedReader reader = new BufferedReader(new InputStreamReader(;

    // Get directory
    Message message[] = folder.getMessages();
    for (int i = 0, n = message.length; i < n; i++) {
      System.out.println(i + ": " + message[i].getFrom()[0] + "\t"
          + message[i].getSubject());

      System.out.println("Read message? [YES to read/QUIT to end]");
      String line = reader.readLine();
      if ("YES".equalsIgnoreCase(line)) {
      } else if ("QUIT".equalsIgnoreCase(line)) {

    // Close connection


Related examples in the same category

1.Pure Java Email client
2.Sending Mail Using Sockets
3.Sending Mail
4.A Client to Send SMTP MailA Client to Send SMTP Mail
5.Mailer: Sends an email message
6.TestOpenMailRelay -- send self-returning SPAM to check for relay sitesTestOpenMailRelay -- send self-returning SPAM to check for relay sites
7.Sender -- send an email message
8.Sender -- send an email message with attachment
9.SendMime -- send a multi-part MIME email message
10.Read a file return mail headers one at a time
11.Send mail using GMAIL
12.Send Mail Implementation using simple SMTP
13.Validator for Zip code, Email, Phone number
14.Send email out