How do I use the JavaMail API to read newsgroups messages?

John Zukowski

  1. Get an NNTP provider. The only one I am aware of is the one provided from knife at http://www.dog.net.uk/knife/.
  2. Place JAR file in CLASSPATH. It has a javamail.providers file already there so you don't need to edit/modify this.
  3. When you get the store, get it as "nttp"
  4. When you get the folder, get the newsgroup you want, like "comp.lang.java.corba"
  5. To get the list of messages in the folder, use folder.getMessages()
Thats basically about it. Treat the newsgroup messages as you would a mail message to read / deal with attachments.

The following program demonstrates:

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

public class GetNewsExample {
  public static void main (String args[])
      throws Exception {
    String host = args[0];
    String username = args[1];
    String password = args[2];
    String newsgroup = args[3];

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

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

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

    // Get folder
    Folder folder = store.getFolder(newsgroup);

    BufferedReader reader = new BufferedReader (
      new InputStreamReader(System.in));

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

        "Do you want to read message?" +
        " [YES to read/QUIT to end]");
      String line = reader.readLine();
      // Mark as deleted if appropriate
      if ("YES".equals(line)) {
      } else if ("QUIT".equals(line)) {

    // Close connection