1. 程式人生 > >利用JavaMail實現郵件的收取

利用JavaMail實現郵件的收取

     昨天寫了一個利用JavaMail傳送郵件的示例,本著有始有終的原則。今天寫了一篇利用JavaMail收取郵件的示例。由於實力有限,程式碼寫的不周到的地方,請大家見亮。本人只是寫了一個簡單的例子,在實際專案開發中,還有很多東西需要讀者自己去斟酌和修改。廢話不多說,直接上程式碼。

1、一些引數配置的常量類

package com.bao.receivemail;

/**
 * 郵件配置的常量類
 */
public class Config {
	
	public static String MAIL_HOST = "pop3.163.com";//伺服器ip
	
	public static int MAIL_PORT = 110;//埠
	
	public static String MAIL_TYPE = "pop3";//服務型別
	
	public static String MAIL_AUTH = "true";
	
	public static String MAIL_ATTACH_PATH = "upload/recMail/";//附件存放目錄
}

2、郵件的收取類

package com.bao.receivemail;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import com.sun.mail.pop3.POP3Message;

/**
 * 郵件的收取類
 */
public class ReceiveMailHandler {
    
	/**
	 * 獲取session會話的方法
	 * @return
	 * @throws Exception
	 */
    private Session getSessionMail() throws Exception {
    	Properties properties = System.getProperties();
    	properties.put("mail.smtp.host", Config.MAIL_HOST);
    	properties.put("mail.smtp.auth", Config.MAIL_AUTH);
    	Session sessionMail = Session.getDefaultInstance(properties, null);
	    return sessionMail;
    }
    
    /**
	 * 接收郵件
	 * @param 郵箱的使用者名稱和密碼
	 * @return 無
	 */
	public void receiveMail(String userName,String passWord) {
    	Store store = null;
    	Folder folder = null;
    	int messageCount = 0;
    	URLName urln = null;
		try{
			//進行使用者郵箱連線
			urln = new URLName(Config.MAIL_TYPE, Config.MAIL_HOST, Config.MAIL_PORT, null,userName,passWord);   
			store = getSessionMail().getStore(urln);   
			store.connect();
			//獲得郵箱內的郵件夾Folder物件,以"只讀"開啟
			folder = store.getFolder("INBOX");//開啟收件箱
			folder.open(Folder.READ_ONLY);//設定只讀
			//獲得郵件夾Folder內的所有郵件個數
			messageCount = folder.getMessageCount();// 獲取所有郵件個數
	        //獲取新郵件處理
			System.out.println("============>>郵件總數:"+messageCount);
			if(messageCount > 0){
				Message[] messages = folder.getMessages(messageCount,messageCount);//讀取最近的一封郵件
				for(int i = 0;i < messages.length;i++) {	
					String content = getMailContent((Part)messages[i]);//獲取內容
				    if (isContainAttach((Part)messages[i])) {
	                	saveAttachMent((Part)messages[i],Config.MAIL_ATTACH_PATH);
	                } 
					System.out.println("=====================>>開始顯示郵件內容<<=====================");
		            System.out.println("傳送人: " + getFrom(messages[i]));
		            System.out.println("主題: " + getSubject(messages[i]));
		            System.out.println("內容: " + content);
		            System.out.println("傳送時間: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(((MimeMessage) messages[i]).getSentDate()));
	                System.out.println("是否有附件: " + (isContainAttach((Part)messages[i]) ? "有附件" : "無附件"));
		            System.out.println("=====================>>結束顯示郵件內容<<=====================");
		            ((POP3Message) messages[i]).invalidate(true);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(folder != null && folder.isOpen()){
				try {
					folder.close(true);
				} catch (MessagingException e) {
					e.printStackTrace();
				}
			}
			if(store.isConnected()){
				try {
					store.close();
				} catch (MessagingException e) {
					e.printStackTrace();
				}
			}
		}
    }
   
	/**
     * 獲得發件人的地址
     * @param message:Message
     * @return 發件人的地址
     */
	private String getFrom(Message message) throws Exception {  
        InternetAddress[] address = (InternetAddress[]) ((MimeMessage) message).getFrom();    
        String from = address[0].getAddress();    
        if (from == null){
        	from = "";
        }
        return from;    
    }
	
	 /**
     * 獲得郵件主題   
     * @param message:Message
     * @return 郵件主題  
     */
	private String getSubject(Message message) throws Exception {
    	String subject = "";
    	if(((MimeMessage) message).getSubject() != null){
    		subject = MimeUtility.decodeText(((MimeMessage) message).getSubject());// 將郵件主題解碼  
    	}
    	return subject;    
    }
	
    /**
     * 獲取郵件內容
     * @param part:Part
     */
	private String getMailContent(Part part) throws Exception {    
		StringBuffer bodytext = new StringBuffer();//存放郵件內容
		//判斷郵件型別,不同型別操作不同
		if (part.isMimeType("text/plain")) {    
            bodytext.append((String) part.getContent());    
        } else if (part.isMimeType("text/html")) {    
            bodytext.append((String) part.getContent());    
        } else if (part.isMimeType("multipart/*")) {    
            Multipart multipart = (Multipart) part.getContent();    
            int counts = multipart.getCount();    
            for (int i = 0; i < counts; i++) {    
                getMailContent(multipart.getBodyPart(i));    
            }    
        } else if (part.isMimeType("message/rfc822")) {    
            getMailContent((Part) part.getContent());    
        } else {}    
        return bodytext.toString();
    }
    
    /**
     * 判斷此郵件是否包含附件 
     * @param part:Part
     * @return 是否包含附件
     */
	private boolean isContainAttach(Part part) throws Exception { 
        boolean attachflag = false;    
        if (part.isMimeType("multipart/*")) {    
            Multipart mp = (Multipart) part.getContent();    
            for (int i = 0; i < mp.getCount(); i++) {    
                BodyPart mpart = mp.getBodyPart(i);    
                String disposition = mpart.getDisposition();    
                if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE))))    
                    attachflag = true;    
                else if (mpart.isMimeType("multipart/*")) {    
                    attachflag = isContainAttach((Part) mpart);    
                } else {    
                    String contype = mpart.getContentType();    
                    if (contype.toLowerCase().indexOf("application") != -1)    
                        attachflag = true;    
                    if (contype.toLowerCase().indexOf("name") != -1)    
                        attachflag = true;    
                }    
            }    
        } else if (part.isMimeType("message/rfc822")) {    
            attachflag = isContainAttach((Part) part.getContent());    
        }    
        return attachflag;    
    }	
	
	 /**
     * 儲存附件
     * @param part:Part
     * @param filePath:郵件附件存放路徑
     */
	private void saveAttachMent(Part part,String filePath) throws Exception {    
    	String fileName = "";
    	//儲存附件到伺服器本地
        if (part.isMimeType("multipart/*")) {    
            Multipart mp = (Multipart) part.getContent();
            for (int i = 0; i < mp.getCount(); i++) {
            	BodyPart mpart = mp.getBodyPart(i);    
                String disposition = mpart.getDisposition();   
                if ((disposition != null) && ((disposition.equals(Part.ATTACHMENT)) || (disposition.equals(Part.INLINE)))) {   
                	fileName = mpart.getFileName();    
                	if (fileName != null) {
                    	fileName = MimeUtility.decodeText(fileName);
                        saveFile(fileName, mpart.getInputStream(),filePath);  
                    }  
                } else if (mpart.isMimeType("multipart/*")) {    
                	saveAttachMent(mpart,filePath);
                } else {
                	fileName = mpart.getFileName();    
                	if (fileName != null) {
                    	fileName = MimeUtility.decodeText(fileName);
                        saveFile(fileName, mpart.getInputStream(),filePath);
                    }    
                }    
            }    
        } else if (part.isMimeType("message/rfc822")) {    
            saveAttachMent((Part) part.getContent(),filePath);    
        }
        
    }
    
    /**
     * 儲存附件到指定目錄裡 
     * @param fileName:附件名稱
     * @param in:檔案輸入流
     * @param filePath:郵件附件存放基路徑
     */
    private void saveFile(String fileName, InputStream in,String filePath) throws Exception {    
    	File storefile = new File(filePath);   
        if(!storefile.exists()){
        	storefile.mkdirs();
    	}
        BufferedOutputStream bos = null;   
        BufferedInputStream bis = null;   
        try {   
            bos = new BufferedOutputStream(new FileOutputStream(filePath + "\\" + fileName));   
            bis = new BufferedInputStream(in);   
            int c;   
            while ((c = bis.read()) != -1) {   
                bos.write(c);   
                bos.flush();   
            }   
        } catch (Exception e) {   
        	throw e;   
        } finally {
        	if(bos != null){
        		bos.close();
        	}
            if(bis != null){
            	bis.close();
            }
        }   
    } 
}

 3、測試程式

package com.bao.main;

import com.bao.receivemail.ReceiveMailHandler;

public class Main {

	public static void main(String[] args) {
		try {
			new ReceiveMailHandler().receiveMail("username", "password");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

執行結果會在控制檯打印出來,只讀取了郵箱中最新的那一封郵件。如果有附件,附件會自動儲存到專案中你設定的檔案目錄中。程式不上傳了,大家自己看下吧!謝謝大家的支援^.^!