java 发送、解析邮件实例(二)

package com.prase.email.eight;

/** 
 * CrazyItTest 
 * 使用JavaMail 编写接收邮件示例 
 */  
import java.io.BufferedReader;  
import java.io.IOException;  
import java.io.InputStreamReader;  
import java.util.Properties;  
import javax.mail.Folder;  
import javax.mail.Message;  
import javax.mail.MessagingException;  
import javax.mail.Session;  
import javax.mail.Store;  


public class ReceiveEmailTest {  
    private static final String  PROTOCOL = "pop3";  
    private static final String  HOST = "pop3.163.com";  
    private static final String USER = "qqhechuanzhen";  
    private static final String PASS = "pass";  
    
    private static Session getMailSession(){  
        Properties props=new Properties();  
        props.put("mail.store.protocol", PROTOCOL);  
        props.put("mail.pop3.host", HOST);  
        
//      使用代理
//      props.setProperty("proxySet","true");
//	    props.setProperty("ProxyHost","10.24.5.105");
//	    props.setProperty("ProxyPort","39002"); 
        
        
        Session session=Session.getDefaultInstance(props);  
        return session;  
    }  
      
      
    private static void receiveEmail() throws MessagingException, IOException{  
        Store store=getMailSession().getStore();  
        store.connect(HOST,USER,PASS);  
          
        Folder receiveFolder=store.getFolder("inbox");//对于POP3协议此参数值只能是inbox  
        receiveFolder.open(Folder.READ_WRITE);//设置收件夹打开后的读写权限  
          
        int messageCount=receiveFolder.getMessageCount();  
        System.out.println("总共拥有邮件数:"+messageCount);  
          
        if(messageCount>0){  
            Message []messages=receiveFolder.getMessages();//得到所有的邮件  
            for(int i=0;i<messages.length;i++){  
                Message msg=messages[i];  
                System.out.println("第"+(i+1)+"封邮件的主题为:"+msg.getSubject()  
                        +" ,其发送人地址为:"+msg.getFrom()[0]);  
                System.out.println("您是否要阅读此邮件?若要请输入yes,否则就输入no:");  
                BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
                String input=br.readLine();  
                if(input!=null && !"".equals(input)  
                        &&"yes".equals(input.trim())){  
                    msg.writeTo(System.out);//直接输出到控制台,当然也输出到文件中。  
                }  
            }  
        }  
        receiveFolder.close(true);//关闭邮件夹对象  
        store.close();//断开连接  
    }  
      
    /** 
     * @param args 
     * @throws IOException  
     * @throws MessagingException  
     */  
    public static void main(String[] args) throws MessagingException, IOException {  
        receiveEmail();  
    }  
}  

你可能感兴趣的:(java,email,folder,store)