1 16 package examples; 17 18 import java.io.BufferedReader ; 19 import java.io.IOException ; 20 import java.io.Reader ; 21 import org.apache.commons.net.pop3.POP3Client; 22 import org.apache.commons.net.pop3.POP3MessageInfo; 23 24 33 public final class messages 34 { 35 36 public static final void printMessageInfo(BufferedReader reader, int id) 37 throws IOException 38 { 39 String line, lower, from, subject; 40 41 from = ""; 42 subject = ""; 43 44 while ((line = reader.readLine()) != null) 45 { 46 lower = line.toLowerCase(); 47 if (lower.startsWith("from: ")) 48 from = line.substring(6).trim(); 49 else if (lower.startsWith("subject: ")) 50 subject = line.substring(9).trim(); 51 } 52 53 System.out.println(Integer.toString(id) + " From: " + from + 54 " Subject: " + subject); 55 } 56 57 public static final void main(String [] args) 58 { 59 int message; 60 String server, username, password; 61 POP3Client pop3; 62 Reader reader; 63 POP3MessageInfo[] messages; 64 65 if (args.length < 3) 66 { 67 System.err.println( 68 "Usage: messages <pop3 server hostname> <username> <password>"); 69 System.exit(1); 70 } 71 72 server = args[0]; 73 username = args[1]; 74 password = args[2]; 75 76 pop3 = new POP3Client(); 77 pop3.setDefaultTimeout(60000); 79 80 try 81 { 82 pop3.connect(server); 83 } 84 catch (IOException e) 85 { 86 System.err.println("Could not connect to server."); 87 e.printStackTrace(); 88 System.exit(1); 89 } 90 91 try 92 { 93 if (!pop3.login(username, password)) 94 { 95 System.err.println("Could not login to server. Check password."); 96 pop3.disconnect(); 97 System.exit(1); 98 } 99 100 messages = pop3.listMessages(); 101 102 if (messages == null) 103 { 104 System.err.println("Could not retrieve message list."); 105 pop3.disconnect(); 106 System.exit(1); 107 } 108 else if (messages.length == 0) 109 { 110 System.out.println("No messages"); 111 pop3.logout(); 112 pop3.disconnect(); 113 System.exit(1); 114 } 115 116 for (message = 0; message < messages.length; message++) 117 { 118 reader = pop3.retrieveMessageTop(messages[message].number, 0); 119 120 if (reader == null) 121 { 122 System.err.println("Could not retrieve message header."); 123 pop3.disconnect(); 124 System.exit(1); 125 } 126 127 printMessageInfo(new BufferedReader (reader), messages[message].number); 128 } 129 130 pop3.logout(); 131 pop3.disconnect(); 132 } 133 catch (IOException e) 134 { 135 e.printStackTrace(); 136 System.exit(1); 137 } 138 } 139 } 140 141 | Popular Tags |