import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;
/**
* <p>Title: 使用JavaMail接收郵件</p>
* <p>Description: 實例JavaMail包接收郵件,本實例沒有實現接收郵件的附件。</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: POPMail.java</p>
* @version 1.0
*/
public class POPMail{
/**
*<br>方法說明:主方法,接收用戶輸入的郵箱服務器、用戶名和密碼
*<br>輸入參數:
*<br>返回類型:
*/
public static void main(String args[]){
try{
String popServer=args[0];
String popUser=args[1];
String popPassword=args[2];
receive(popServer, popUser, popPassword);
}catch (Exception ex){
System.out.println("Usage: java com.lotontech.mail.POPMail"+" popServer popUser popPassword");
}
System.exit(0);
}
/**
*<br>方法說明:接收郵件信息
*<br>輸入參數:
*<br>返回類型:
*/
public static void receive(String popServer, String popUser, String popPassword){
Store store=null;
Folder folder=null;
try{
//獲取默認會話
Properties props = System.getProperties();
Session session = Session.getDefaultInstance(props, null);
//使用POP3會話機制,連接服務器
store = session.getStore("pop3");
store.connect(popServer, popUser, popPassword);
//獲取默認文件夾
folder = store.getDefaultFolder();
if (folder == null) throw new Exception("No default folder");
//如果是收件箱
folder = folder.getFolder("INBOX");
if (folder == null) throw new Exception("No POP3 INBOX");
//使用只讀方式打開收件箱
folder.open(Folder.READ_ONLY);
//得到文件夾信息,獲取郵件列表
Message[] msgs = folder.getMessages();
for (int msgNum = 0; msgNum < msgs.length; msgNum++){
printMessage(msgs[msgNum]);
}
}catch (Exception ex){
ex.printStackTrace();
}
finally{
//釋放資源
try{
if (folder!=null) folder.close(false);
if (store!=null) store.close();
}catch (Exception ex2) {
ex2.printStackTrace();
}
}
}
/**
*<br>方法說明:打印郵件信息
*<br>輸入參數:Message message 信息對象
*<br>返回類型:
*/
public static void printMessage(Message message){
try{
//獲得發送郵件地址
String from=((InternetAddress)message.getFrom()[0]).getPersonal();
if (from==null) from=((InternetAddress)message.getFrom()[0]).getAddress();
System.out.println("FROM: "+from);
//獲取主題
String subject=message.getSubject();
System.out.println("SUBJECT: "+subject);
//獲取信息對象
Part messagePart=message;
Object content=messagePart.getContent();
//附件
if (content instanceof Multipart){
messagePart=((Multipart)content).getBodyPart(0);
System.out.println("[ Multipart Message ]");
}
//獲取content類型
String contentType=messagePart.getContentType();
//如果郵件內容是純文本或者是HTML,那麼打印出信息
System.out.println("CONTENT:"+contentType);
if (contentType.startsWith("text/plain")||
contentType.startsWith("text/html")){
InputStream is = messagePart.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
String thisLine=reader.readLine();
while (thisLine!=null){
System.out.println(thisLine);
thisLine=reader.readLine();
}
}
System.out.println("-------------- END ---------------");
}catch (Exception ex){
ex.printStackTrace();
}
}
}