监视电子邮件帐户
import java.util.Arrays; import java.util.Properties;/* 来自 n o w j a v a . c o m - 时代Java*/ import javax.mail.Address; 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 javax.mail.internet.InternetAddress; public class Main { boolean shouldContinue = true; Thread mailCheckingThread = null; public static void main(String[] args) { Main recipe = new Main(); recipe.start(); } public void start() {/**来自 时代Java**/ mailCheckingThread = new Thread(() -> { while (shouldContinue) { checkForMail(); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } }); mailCheckingThread.start(); } public void stop() { shouldContinue = false; mailCheckingThread.interrupt(); try { mailCheckingThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } private void checkForMail() { Properties properties = new Properties(); String username = "mymodule"; String password = "java9test"; String folder = "Inbox"; String host = "imap.gmail.com"; try { Session session = Session.getDefaultInstance(properties, null); Store store = session.getStore("imaps"); store.connect(host, username, password); Folder inbox = store.getFolder(folder); inbox.open(Folder.READ_WRITE); int messageCount = inbox.getMessageCount(); Message messages[] = inbox.getMessages(1, messageCount); for (Message message : messages) { boolean hasBeenRead = false; if (Arrays.asList(message.getFlags().getSystemFlags()).contains( Flags.Flag.SEEN)) { continue; // not interested in "seen" messages } if (processMessage(message)) { System.out.println("Processed :" + message.getSubject()); message.setFlag(Flags.Flag.DELETED, true); } else { System.out.println("Couldn't Understand :" + message.getSubject()); // set it as seen, but keep it around message.setFlag(Flags.Flag.SEEN, true); } } inbox.close(true); } catch (MessagingException e) { e.printStackTrace(); } } private boolean processMessage(Message message) throws MessagingException { boolean result = false; String subject = message.getSubject().toLowerCase(); if (subject.startsWith("subscribe")) { String emailAddress = extractEmail(message.getFrom()); if (emailAddress != null) { System.out.println("Subscribing for :" + emailAddress); result = true; } } else if (subject.startsWith("unsubscribe")) { String emailAddress = ex