자바 메 일 수신 기 (pop 3)

11348 단어 자바sun


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.FetchProfile;
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.UIDFolder;

import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;

import com.sun.mail.pop3.POP3Folder;

/**
 *      ,      :<code>open->receive->close</code>。
 */
public class MailReceiver {
	public static final String POP3 = "pop3";
	public static final String INBOX = "INBOX";

	private String pop;
	private String serverName;
	private String serverPasswd;
	private MessageFilter msgFilter;

	/**
	 *           
	 */
	private String attachSavePath;

	private Store store;
	private POP3Folder inbox;
	private FetchProfile profile;

	/**
	 *    (     ,            )
	 * 
	 * @param pop
	 *            POP Server URL
	 * @param serverName
	 *               
	 * @param serverPasswd
	 *              
	 * @param msgFilter
	 *                 ,<code>null</code>     
	 */
	public MailReceiver(String pop, String serverName, String serverPasswd) {
		this(pop, serverName, serverPasswd, null, null);
	}

	/**
	 *    (     )
	 * 
	 * @param pop
	 *            POP Server URL
	 * @param serverName
	 *               
	 * @param serverPasswd
	 *              
	 * @param msgFilter
	 *                 ,<code>null</code>     
	 */
	public MailReceiver(String pop, String serverName, String serverPasswd,
			MessageFilter msgFilter) {
		this(pop, serverName, serverPasswd, msgFilter, null);
	}

	/**
	 *    (            )
	 * 
	 * @param pop
	 *            POP Server URL
	 * @param serverName
	 *               
	 * @param serverPasswd
	 *              
	 * @param attachSavePath
	 *                  ,<code>null</code>       
	 */
	public MailReceiver(String pop, String serverName, String serverPasswd,
			String attachSavePath) {
		this(pop, serverName, serverPasswd, null, attachSavePath);
	}

	/**
	 *    
	 * 
	 * @param pop
	 *            POP Server URL
	 * @param serverName
	 *               
	 * @param serverPasswd
	 *              
	 * @param msgFilter
	 *                 ,<code>null</code>     
	 * @param attachSavePath
	 *                  ,<code>null</code>       
	 */
	public MailReceiver(String pop, String serverName, String serverPasswd,
			MessageFilter msgFilter, String attachSavePath) {
		super();
		Assert.hasLength(pop, "Pop");
		Assert.hasLength(serverName, "ServerName");
		Assert.hasLength(serverPasswd, "ServerPasswd");

		this.pop = pop;
		this.serverName = serverName;
		this.serverPasswd = serverPasswd;
		this.msgFilter = msgFilter;
		this.attachSavePath = attachSavePath;
	}

	/**
	 *        ,  INBOX
	 */
	public void open() throws MessagingException {
		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);

		this.store = session.getStore(POP3);
		store.connect(pop, serverName, serverPasswd);

		this.inbox = (POP3Folder) store.getFolder(INBOX);
		inbox.open(Folder.READ_ONLY);

		this.profile = new FetchProfile();
		profile.add(UIDFolder.FetchProfileItem.UID);
		profile.add(FetchProfile.Item.ENVELOPE);
	}

	/**
	 *     ,           ,       INOBX   。<br>
	 *    {@link #close()}    INBOX   。
	 * 
	 * @throws UnsupportedEncodingException
	 * @throws IOException
	 * @throws MessagingException
	 */
	public List<Message> receive() throws UnsupportedEncodingException,
			IOException, MessagingException {
		//      UID
		Message[] messages = inbox.getMessages();
		inbox.fetch(messages, profile);

		//     
		List<Message> msgList = new ArrayList<Message>();
		for (Message msg : messages) {
			if (msgFilter == null || msgFilter.filte(inbox, msg)) {
				//     
				if (StringUtils.hasLength(attachSavePath)
						&& MailUtils.containsAttach(msg)) {
					saveAttachment(msg);
				}
				msgList.add(msg);
			}
		}

		return msgList;
	}

	/**
	 *   INBOX   。
	 */
	public void close() {
		try {
			inbox.close(false);
			store.close();
		} catch (MessagingException e) {
			throw new MailException("  INBOX     ", e);
		}
	}

	public POP3Folder getInbox() {
		return inbox;
	}

	/**
	 *     
	 * 
	 * @throws Exception
	 * @throws IOException
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 */
	private void saveAttachment(Part part) throws UnsupportedEncodingException,
			MessagingException, IOException {
		if (part.isMimeType("multipart/*")) {
			String filename = "";
			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 = MailUtils.decodeText(mpart.getFileName());
					saveFile(filename, mpart.getInputStream());
				} else if (mpart.isMimeType("multipart/*")) {
					saveAttachment(mpart);
				} else {
					filename = MailUtils.decodeText(mpart.getFileName());
					if (filename != mpart.getFileName()) {
						saveFile(filename, mpart.getInputStream());
					}
				}
			}
		} else if (part.isMimeType("message/rfc822")) {
			saveAttachment((Part) part.getContent());
		}
	}

	/**
	 *          
	 * 
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	private void saveFile(String filename, InputStream in)
			throws FileNotFoundException, IOException {
		File file = new File(attachSavePath + File.separator + filename);
		FileCopyUtils.copy(in, new FileOutputStream(file));
	}
}

import javax.mail.Message;
import javax.mail.MessagingException;

import com.sun.mail.pop3.POP3Folder;

/**
 *       ,                。
 */
public interface MessageFilter {
	/**
	 *     
	 * 
	 * @param box
	 *                 
	 * @param message
	 *                
	 * @return          ,  <code>true</code>,    <code>false</code>
	 */
	boolean filte(POP3Folder box, Message message)  throws MessagingException;
}


import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.mail.BodyPart;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.internet.MimeUtility;

import org.springframework.util.Assert;

/**
 *        
 */
public class MailUtils {
	private MailUtils() {

	}

	/**
	 * <code>MimeUtility.decodeText(text)</code>
	 */
	public static String decodeText(String text)
			throws UnsupportedEncodingException {
		if (text == null)
			return null;

		String s = text.toLowerCase();
		if (s.contains("gb2312") || s.contains("gbk")) {
			return MimeUtility.decodeText(text);
		}

		return text;
	}

	/**
	 *           
	 * 
	 * @throws IOException
	 * @throws MessagingException
	 */
	public static boolean containsAttach(Part part) throws MessagingException,
			IOException {
		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 = containsAttach((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 = containsAttach((Part) part.getContent());
		}
		return attachflag;
	}

	/**
	 *     ,           <code>bodyText</code>   .<br>
	 *   MimeType              .
	 * 
	 * @throws IOException
	 * @throws MessagingException
	 */
	public static void getMailContent(Part part, StringBuffer bodyText)
			throws MessagingException, IOException {
		Assert.notNull(bodyText, "bodyText");
		String contenttype = part.getContentType();
		int nameindex = contenttype.indexOf("name");
		boolean conname = false;
		if (nameindex != -1)
			conname = true;

		if (part.isMimeType("text/plain") && !conname) {
			bodyText.append((String) part.getContent());
		} else if (part.isMimeType("text/html") && !conname) {
			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), bodyText);
			}
		} else if (part.isMimeType("message/rfc822")) {
			getMailContent((Part) part.getContent(), bodyText);
		}
	}
}

좋은 웹페이지 즐겨찾기