Java tutorial
/* * Copyright (c) 2014 szmslab * * This software is released under the MIT License. * http://opensource.org/licenses/mit-license.php */ package com.szmslab.quickjavamail.receive; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Store; import org.apache.commons.lang3.StringUtils; import com.szmslab.quickjavamail.utils.MailProperties; /** * JavaMail????? * * @author szmslab */ public class MailReceiver { /** * JavaMail? */ private MailProperties properties; /** * ??? */ private boolean isDebug = false; /** * ? */ private boolean useDefaultSession = true; /** * ???? */ private String folderName = "INBOX"; /** * ???????? */ private boolean readonly = true; /** * ?? * * @param properties * JavaMail? */ public MailReceiver(MailProperties properties) { this.properties = properties; } /** * ?????? * * @param isDebug * ?????? * @return ? */ public MailReceiver debug(boolean isDebug) { this.isDebug = isDebug; return this; } /** * ???? * * @param useDefaultSession * ?????? * @return ? */ public MailReceiver useDefaultSession(boolean useDefaultSession) { this.useDefaultSession = useDefaultSession; return this; } /** * ??????? * * @param folderName * ???? * @return ? */ public MailReceiver folderName(String folderName) { if (StringUtils.isNotBlank(folderName)) { this.folderName = folderName; } return this; } /** * ??????????? * * @param readonly * ???????? * @return ? */ public MailReceiver readonly(boolean readonly) { this.readonly = readonly; return this; } /** * ???? * * @param callback * ??1??? * @throws Exception */ public void execute(ReceiveIterationCallback callback) throws Exception { final Session session = useDefaultSession ? Session.getDefaultInstance(properties.getProperties(), properties.getAuthenticator()) : Session.getInstance(properties.getProperties(), properties.getAuthenticator()); session.setDebug(isDebug); Store store = null; Folder folder = null; try { store = session.getStore(properties.getProtocol()); store.connect(); folder = store.getFolder(folderName); folder.open(readonly ? Folder.READ_ONLY : Folder.READ_WRITE); final Message messages[] = folder.getMessages(); for (Message message : messages) { MessageLoader loader = new MessageLoader(message, !readonly); boolean isContinued = callback.iterate(loader); if (!readonly && loader.isDeleted()) { message.setFlag(Flags.Flag.DELETED, loader.isDeleted()); } if (!isContinued) { break; } } } finally { if (folder != null) { try { folder.close(!readonly); } catch (MessagingException e) { System.out.println(e); } } if (store != null) { try { store.close(); } catch (MessagingException e) { System.out.println(e); } } } } }