Java Reference
In-Depth Information
public static void main ( String [] args ) {
if ( args . length == 0 ) {
System . err . println (
"Usage: java MailClient protocol://username:password@host/foldername" );
return ;
}
URLName server = new URLName ( args [ 0 ]);
try {
Session session = Session . getInstance ( new Properties ());
// Connect to the server and open the folder
Folder folder = session . getFolder ( server );
if ( folder == null ) {
System . out . println ( "Folder " + server . getFile () + " not found." );
System . exit ( 1 );
}
folder . open ( Folder . READ_ONLY );
// Get the messages from the server
Message [] messages = folder . getMessages ();
for ( int i = 0 ; i < messages . length ; i ++) {
System . out . println ( "------------ Message " + ( i + 1 )
+ " ------------" );
messages [ i ]. writeTo ( System . out );
}
// Close the connection
// but don't remove the messages from the server
folder . close ( false );
} catch ( IOException | MessagingException ex ) {
ex . printStackTrace ();
}
}
}
URLName does make the code a little more compact since it moves some information
from the source code to the command line. Besides eliminating the obvious variables
and string literals for username, host, and so forth, we've managed to eliminate any
direct reference to the Store class. A typical run starts like this:
% java MailClient pop3://eharold:mypassword@utopia.poly.edu/INBOX
------------ Message 1 ------------
Received: (from eharold@localhost)
by utopia.poly.edu (8.8.8/8.8.8) id QAA05728
for eharold; Mon, 30 Nov 2009 16:14:29 -0500 (EST)
Date: Mon, 30 Nov 2009 16:14:29 -0500 (EST)
From: Elliotte Harold <eharold@utopia.poly.edu>
Message-Id: <200911302114.QAA05728@utopia.poly.edu>
To: eharold@utopia.poly.edu
Search WWH ::




Custom Search