Java Reference
In-Depth Information
and MimeMessage classes. For now, we'll do just about the simplest thing imaginable:
print each message on System.out using the message's writeTo() method:
for ( int i = 0 ; i < messages . length ; i ++) {
System . out . println ( "------------ Message " + ( i + 1 )
+ " ------------" );
messages [ i ]. writeTo ( System . out );
}
Once you're done with the messages, close the folder and then close the message store
with the aptly named close() methods:
inbox . close ( false );
store . close ();
The false argument to the folder's close() method indicates that we do not want the
server to actually expunge any deleted messages in the folder. We simply want to break
our connection to this folder.
Example 3-1 puts this all together with a basic program that downloads and prints out
the contents of a specified POP mailbox. Messages are simply dumped on Sys
tem.out in the default encoding. The servers, usernames, and so forth are all hardcoded.
This quickly demonstrates most of the key points of receiving mail with the JavaMail
API. A more advanced program would include an appropriate GUI.
Example 3-1. POP3Client
import javax.mail.* ;
import java.util.* ;
import java.io.* ;
public class POP3Client {
public static void main ( String [] args ) {
Properties props = new Properties ();
String host = "utopia.poly.edu" ;
String username = "eharold" ;
String password = "mypassword" ;
String provider = "pop3" ;
try {
// Connect to the POP3 server
Session session = Session . getInstance ( props );
Store store = session . getStore ( provider );
store . connect ( host , username , password );
// Open the folder
Folder inbox = store . getFolder ( "INBOX" );
if ( inbox == null ) {
System . out . println ( "No INBOX" );
Search WWH ::




Custom Search