Java Reference
In-Depth Information
// Enumerate parts
Object body = messages [ i ]. getContent ();
if ( body instanceof Multipart ) {
processMultipart (( Multipart ) body );
} else { // ordinary message
processPart ( messages [ i ]);
}
System . out . println ();
}
} catch ( MessagingException | IOException ex ) {
ex . printStackTrace ();
} finally {
// Close the connection
// but don't remove the messages from the server
if ( folder != null && folder . isOpen ())
try {
folder . close ( false );
} catch ( MessagingException e ) {
// ignore;
}
}
// Since we may have brought up a GUI to authenticate,
// we can't rely on returning from main() to exit
System . exit ( 0 );
}
public static void processMultipart ( Multipart mp )
throws MessagingException {
for ( int i = 0 ; i < mp . getCount (); i ++) {
processPart ( mp . getBodyPart ( i ));
}
}
public static void processPart ( Part p ) {
try {
// I'd prefer to test the Content-Disposition header here.
// However, too many common email clients don't use it.
String fileName = p . getFileName ();
if ( fileName == null ) { // likely inline
p . writeTo ( System . out );
} else if ( fileName != null ) {
File f = new File ( fileName );
// find a version that does not yet exist
for ( int i = 1 ; f . exists (); i ++) {
String newName = fileName + " " + i ;
f = new File ( newName );
}
try ( FileOutputStream out = new FileOutputStream ( f );
InputStream in = new BufferedInputStream ( p . getInputStream ())) {
Search WWH ::




Custom Search