Saturday, January 10, 2009

JavaMail API Checking for Mail

JavaMail API Checking for Mail

Tasks

------

1. Starting with the skeleton code, get or create a Properties object.

2. Get a Session object based on the Properties.

3. Get a Store for your email protocol, either pop3 or imap.

4. Connect to your mail host's store with the appropriate username and password.

5. Get the folder you want to read. More than likely, this will be the INBOX.

6. Open the folder read-only.

7. Get a directory of the messages in the folder. Save the message list in an array variable named message.

8. For each message, display the from field and the subject.

9. Display the message content when prompted.

10. Close the connection to the folder and store.

11. Compile and run the program, passing your mail server, username, and password on the command line. Answer YES to the messages you want to read. Just hit ENTER if you don't. If you want to stop reading your mail before making your way through all the messages, enter QUIT.

import java.io.*;

import java.util.Properties;

import javax.mail.*;

import javax.mail.internet.*;

public class GetMessageExample {

public static void main (String args[]) throws Exception {

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");

// Connect to store

store.connect(host, username, password);

// Get folder

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

// Open read-only

folder.open(Folder.READ_ONLY);

BufferedReader reader = new BufferedReader (

new InputStreamReader(System.in));

// Get directory

Message message[] = folder.getMessages();

for (int i=0, n=message.length; i

// Display from field and subject

System.out.println(i + ": " + message[i].getFrom()[0]

+ "\t" + message[i].getSubject());

System.out.println("Do you want to read message? [YES to read/QUIT to end]");

String line = reader.readLine();

if ("YES".equals(line)) {

// Display message content

System.out.println(message[i].getContent());

} else if ("QUIT".equals(line)) {

break;

}

}

// Close connection

folder.close(false);

store.close();

}

}

Demonstration.

---------------

After executing the following command (replacing the mail server, username, and password):

java GetMessageExample POP.Server username password

You'll be prompted to read the messages in your INBOX. Enter YES to see the message content.

0: president@whitehouse.gov Thanks.

Do you want to read message? [YES to read/QUIT to end]

YES

Blah Blah Blah

...

1: billg@microsoft.com No Thanks.

Do you want to read message? [YES to read/QUIT to end]

YES

Blah Blah Blah Blah



********************************************************

No comments:

Post a Comment