POP3協議容許電子郵件客戶端下載服務器上的郵件, 可是在客戶端的操做[如移動郵件, 標記已讀等), 不會反饋到服務器上html
IMAP協議提供WebMail與電子郵件客戶端之間的雙向通訊, 客戶端的操做都會同步反應到服務器上, 對郵件進行的操做, 服務器上的郵件也會作相應的動做, 好比在客戶端收取了郵箱中的3封郵件, 並將其中一封標記爲已讀, 將另外兩封標記爲刪除, 這些操做會即時反饋到服務器上java
兩種協議相比, IMAP協議更爲便捷和可靠, POP3容易丟失郵件或屢次下載相同的郵件, 但IMAP協議經過郵件客戶端, 與WebMail之間的雙向同步功能很好地避免了這些問題
服務器
/******************************************************************************** * Project Name [JavaEE_Components] * File Name [CheckingMailsByPop3.java] * Creation Date [2015-01-01] * * Copyright© ge.y.yang@gmail.com All Rights Reserved * * Work hard, play harder, think big and keep fit ********************************************************************************/ package javamail.mail; import java.util.Properties; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Session; import javax.mail.Store; import org.junit.Before; import org.junit.Test; import javamail.utils.MailConstants; import javamail.utils.PasswordUtils; /** * 使用POP3協議查看郵件 * * @author 不落的太陽(Sean Yang aka ShortPeace) * @version 1.0 * @since jdk 1.8 * */ public class CheckingMailsByPop3 { private static Properties properties = null; private static String emailAddress = "javamail_sns@sina.com"; @Before public void init() { properties = new Properties(); properties.put("mail.store.protocol", MailConstants.PROTOCAL_POP3); properties.put("mail.pop3.host", MailConstants.POP3_HOST_OF_SINA); properties.put("mail.pop3.port", MailConstants.POP3_PORT_OF_SINA); properties.put("mail.pop3.auth", MailConstants.IS_AUTHORIZATION_NEED); properties.put("mail.debug", String.valueOf(MailConstants.IS_DEBUG_MOD_ENABLED)); } /** * 使用POP3協議查看郵件併發送反饋 * * @throws Exception */ public static void checkMailsByPop3() throws Exception { // 建立Session對象並鏈接到指定的郵箱 Session session = Session.getInstance(properties); Store store = session.getStore(MailConstants.PROTOCAL_POP3); store.connect(emailAddress, PasswordUtils.readPassword(emailAddress)); // 得到收件箱 Folder folder = store.getFolder("INBOX"); // 以只讀權限打開收件箱, 還能夠配置爲Folder.READ_WRITE folder.open(Folder.READ_ONLY); // POP3協議沒法獲知郵件的狀態 // getUnreadMessageCount獲得的是收件箱的郵件總數, // getNewMessageCount和getDeletedMessageCount均爲0 System.out.println("一共有郵件" + folder.getMessageCount() + "封"); System.out.println("新郵件有" + folder.getNewMessageCount() + "封"); System.out.println("未讀郵件有" + folder.getUnreadMessageCount() + "封"); System.out.println("刪除郵件有" + folder.getDeletedMessageCount() + "封"); // 得到全部郵件 Message[] messages = folder.getMessages(); System.out.println("郵件數" + messages.length); folder.close(true); store.close(); } @Test public void testCheckMailsByPop3() throws Exception { checkMailsByPop3(); } }
/******************************************************************************** * Project Name [JavaEE_Components] * File Name [CheckingMailsByImap.java] * Creation Date [2015-01-01] * * Copyright© ge.y.yang@gmail.com All Rights Reserved * * Work hard, play harder, think big and keep fit ********************************************************************************/ package javamail.mail; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Properties; import javax.mail.Flags.Flag; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.MimeUtility; import org.junit.Before; import org.junit.Test; import com.sun.mail.imap.IMAPMessage; import javamail.utils.MailConstants; import javamail.utils.MailUtils; import javamail.utils.PasswordUtils; /** * 使用IMAP協議查看郵件 * * @author 不落的太陽(Sean Yang aka ShortPeace) * @version 1.0 * @since jdk 1.8 * */ public class CheckingMailsByImap { private static Properties properties = null; private static String emailAddress = "javamail_sns@sina.com"; @Before public void init() { properties = new Properties(); properties.put("mail.store.protocol", MailConstants.PROTOCAL_IMAP); properties.put("mail.imap.host", MailConstants.IMAP_HOST_OF_SINA); properties.put("mail.imap.port", MailConstants.IMAP_PORT_OF_SINA); properties.put("mail.imap.auth", MailConstants.IS_AUTHORIZATION_NEED); properties.put("mail.debug", String.valueOf(MailConstants.IS_DEBUG_MOD_ENABLED)); } /** * 使用IMAP協議查看郵件併發送反饋 * * @throws Exception */ public static void checkMailsByImap() throws Exception { // 建立Session對象並鏈接到指定的郵箱 Session session = Session.getInstance(properties); Store store = session.getStore("imap"); store.connect(emailAddress, PasswordUtils.readPassword(emailAddress)); // 得到收件箱 Folder folder = store.getFolder("INBOX"); // 打開收件箱 folder.open(Folder.READ_WRITE); // 獲取郵件列表 System.out.println("一共有郵件" + folder.getMessageCount() + "封"); System.out.println("新郵件有" + folder.getNewMessageCount() + "封"); System.out.println("未讀郵件有" + folder.getUnreadMessageCount() + "封"); System.out.println("刪除郵件有" + folder.getDeletedMessageCount() + "封"); // 得到全部郵件並解析 Message[] messages = folder.getMessages(); for (Message message : messages) { IMAPMessage imapMessage = (IMAPMessage) message; String subject = MimeUtility.decodeText(imapMessage.getSubject()); boolean isSeen = MailUtils.isSeen(imapMessage); if (!isSeen) { System.out.println("[" + subject + "]未讀, 如今開始讀嗎?"); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String answer = reader.readLine(); if ("yes".equalsIgnoreCase(answer)) { // 將郵件標爲已讀, 並向服務器發送反饋 message.setFlag(Flag.SEEN, true); } } } folder.close(true); store.close(); } @Test public void testCheckMailsByImap() throws Exception { checkMailsByImap(); } }
修改以前定義的MailUtils, 增長相應的解析方法session
因爲超出博文限制, 下一篇會單獨列出併發
/******************************************************************************** * Project Name [JavaEE_Components] * File Name [ReplyingMails.java] * Creation Date [2015-01-01] * * Copyright© ge.y.yang@gmail.com All Rights Reserved * * Work hard, play harder, think big and keep fit ********************************************************************************/ package javamail.mail; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Date; import java.util.Properties; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Message.RecipientType; import javax.mail.Session; import javax.mail.Store; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility; import org.junit.Before; import org.junit.Test; import javamail.utils.MailConstants; import javamail.utils.PasswordUtils; /** * 使用POP3和SMTP協議來回復郵件<br/> * * POP3協議負責讀取原郵件<br/> * SMTP協議負責回覆原郵件<br/> * * @author 不落的太陽(Sean Yang aka ShortPeace) * @version 1.0 * @since jdk 1.8 * */ public class ReplyingMails { private static Properties properties; private static String emailAddress = "javamail_sns@sina.com"; @Before public void init() { properties = new Properties(); properties.put("mail.store.protocol", MailConstants.PROTOCAL_POP3); properties.put("mail.pop3.host", MailConstants.POP3_HOST_OF_SINA); properties.put("mail.pop3.port", MailConstants.POP3_PORT_OF_SINA); properties.put("mail.pop3.auth", MailConstants.IS_AUTHORIZATION_NEED); properties.put("mail.smtp.host", MailConstants.SMTP_HOST_OF_SINA); properties.put("mail.smtp.port", MailConstants.SMTP_PORT_OF_SINA); properties.put("mail.smtp.auth", MailConstants.IS_AUTHORIZATION_NEED); properties.put("mail.debug", String.valueOf(MailConstants.IS_DEBUG_MOD_ENABLED)); } /** * 回覆郵件 * * @throws Exception */ public static void replayMails() throws Exception { Session session = Session.getInstance(properties); Store store = session.getStore(MailConstants.PROTOCAL_POP3); store.connect(emailAddress, PasswordUtils.readPassword(emailAddress)); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); Message[] messages = folder.getMessages(); if (messages != null && messages.length > 0) { for (Message message : messages) { String from = InternetAddress.toString(message.getFrom()); if (from != null) { System.out.println("發件人: " + MimeUtility.decodeText(from)); } String replayTo = InternetAddress.toString(message.getReplyTo()); if (replayTo != null) { System.out.println("回覆: " + MimeUtility.decodeText(replayTo)); } String to = InternetAddress.toString(message.getRecipients(RecipientType.TO)); System.out.println("收件人: " + MimeUtility.decodeText(to)); String subject = message.getSubject(); if (subject != null) { System.out.println("主題: " + MimeUtility.decodeText(subject)); } Date sendDate = message.getSentDate(); if (sendDate != null) { System.out.println("發送時間: " + sendDate); } System.out.println("肯定要回復麼?"); String answer = reader.readLine(); if ("yes".equalsIgnoreCase(answer)) { MimeMessage replayMessage = new MimeMessage(session); replayMessage = (MimeMessage) message.reply(false); replayMessage.setFrom(new InternetAddress(to)); replayMessage.setText("這是一封郵件回覆..."); replayMessage.setReplyTo(message.getReplyTo()); Transport transport = session.getTransport(MailConstants.PROTOCOL_SMTP); transport.connect(MailConstants.SMTP_HOST_OF_SINA, emailAddress, PasswordUtils.readPassword(emailAddress)); transport.sendMessage(replayMessage, replayMessage.getAllRecipients()); transport.close(); } else { break; } } } folder.close(true); store.close(); } @Test public void testReplayMails() throws Exception { replayMails(); } }
/******************************************************************************** * Project Name [JavaEE_Components] * File Name [ForwardingMails.java] * Creation Date [2015-01-01] * * Copyright© ge.y.yang@gmail.com All Rights Reserved * * Work hard, play harder, think big and keep fit ********************************************************************************/ package javamail.mail; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Date; import java.util.Properties; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Message.RecipientType; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.Store; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import javax.mail.internet.MimeUtility; import org.junit.Before; import org.junit.Test; import javamail.utils.MailConstants; import javamail.utils.PasswordUtils; /** * 使用POP3和SMTP協議來轉發郵件<br/> * * POP3協議負責讀取原郵件<br/> * SMTP協議負責轉發原郵件<br/> * * @author 不落的太陽(Sean Yang aka ShortPeace) * @version 1.0 * @since jdk 1.8 * */ public class ForwardingMails { private static Properties properties; private static String emailAddress = "javamail_sns@sina.com"; @Before public void init() { properties = new Properties(); properties.put("mail.store.protocol", MailConstants.PROTOCAL_POP3); properties.put("mail.pop3.host", MailConstants.POP3_HOST_OF_SINA); properties.put("mail.pop3.port", MailConstants.POP3_PORT_OF_SINA); properties.put("mail.pop3.auth", MailConstants.IS_AUTHORIZATION_NEED); properties.put("mail.smtp.host", MailConstants.SMTP_HOST_OF_SINA); properties.put("mail.smtp.port", MailConstants.SMTP_PORT_OF_SINA); properties.put("mail.smtp.auth", MailConstants.IS_AUTHORIZATION_NEED); properties.put("mail.debug", String.valueOf(MailConstants.IS_DEBUG_MOD_ENABLED)); } /** * 轉發郵件 * * @throws Exception */ public static void fowrardMails() throws Exception { Session session = Session.getInstance(properties); Store store = session.getStore(MailConstants.PROTOCAL_POP3); store.connect(emailAddress, PasswordUtils.readPassword(emailAddress)); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); Message[] messages = folder.getMessages(); if (messages != null && messages.length > 0) { for (Message message : messages) { String from = InternetAddress.toString(message.getFrom()); if (from != null) { System.out.println("發件人: " + MimeUtility.decodeText(from)); } String replayTo = InternetAddress.toString(message.getReplyTo()); if (replayTo != null) { System.out.println("回覆: " + MimeUtility.decodeText(replayTo)); } String to = InternetAddress.toString(message.getRecipients(RecipientType.TO)); System.out.println("收件人: " + MimeUtility.decodeText(to)); String subject = message.getSubject(); if (subject != null) { System.out.println("主題: " + MimeUtility.decodeText(subject)); } Date sendDate = message.getSentDate(); if (sendDate != null) { System.out.println("發送時間: " + sendDate); } System.out.println("肯定要轉發麼?"); String answer = reader.readLine(); if ("yes".equalsIgnoreCase(answer)) { MimeMessage forwardMessage = new MimeMessage(session); forwardMessage.setRecipients(RecipientType.TO, InternetAddress.parse(from)); forwardMessage.setFrom(new InternetAddress(to)); forwardMessage.setSubject("轉發: " + subject); MimeBodyPart messageBodyPart = new MimeBodyPart(); Multipart multipart = new MimeMultipart(); messageBodyPart.setContent(message, "message/rfc822"); multipart.addBodyPart(messageBodyPart); forwardMessage.setContent(multipart); forwardMessage.saveChanges(); Transport transport = session.getTransport(MailConstants.PROTOCOL_SMTP); transport.connect(MailConstants.SMTP_HOST_OF_SINA, emailAddress, PasswordUtils.readPassword(emailAddress)); transport.sendMessage(forwardMessage, forwardMessage.getAllRecipients()); transport.close(); } else { break; } } } folder.close(true); store.close(); } @Test public void testForwardMails() throws Exception { fowrardMails(); } }
/******************************************************************************** * Project Name [JavaEE_Components] * File Name [DeletingMails.java] * Creation Date [2015-01-01] * * Copyright© ge.y.yang@gmail.com All Rights Reserved * * Work hard, play harder, think big and keep fit ********************************************************************************/ package javamail.mail; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Date; import java.util.Properties; import javax.mail.Flags; import javax.mail.Folder; import javax.mail.Message; import javax.mail.Message.RecipientType; import javax.mail.Session; import javax.mail.Store; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeUtility; import org.junit.Before; import org.junit.Test; import javamail.utils.MailConstants; import javamail.utils.PasswordUtils; /** * 刪除郵件, 更新郵件狀態<br/> * * 有關郵件狀態的一些標記<br/> * Flags.Flag.ANSWERED<br/> * Flags.Flag.DELETED<br/> * Flags.Flag.DRAFT<br/> * Flags.Flag.FLAGGED<br/> * Flags.Flag.RECENT<br/> * Flags.Flag.SEEN<br/> * Flags.Flag.USER<br/> * * @author 不落的太陽(Sean Yang aka ShortPeace) * @version 1.0 * @since jdk 1.8 * */ public class DeletingMails { private static Properties properties; private static String emailAddress = "javamail_sns@sina.com"; @Before public void init() { properties = new Properties(); properties.put("mail.store.protocol", MailConstants.PROTOCAL_POP3); properties.put("mail.pop3.host", MailConstants.POP3_HOST_OF_SINA); properties.put("mail.pop3.port", MailConstants.POP3_PORT_OF_SINA); properties.put("mail.pop3.auth", MailConstants.IS_AUTHORIZATION_NEED); properties.put("mail.smtp.host", MailConstants.SMTP_HOST_OF_SINA); properties.put("mail.smtp.port", MailConstants.SMTP_PORT_OF_SINA); properties.put("mail.smtp.auth", MailConstants.IS_AUTHORIZATION_NEED); properties.put("mail.debug", String.valueOf(MailConstants.IS_DEBUG_MOD_ENABLED)); } /** * 刪除郵件 * * @throws Exception */ public static void deleteMails() throws Exception { Session session = Session.getInstance(properties); Store store = session.getStore(MailConstants.PROTOCAL_POP3); store.connect(emailAddress, PasswordUtils.readPassword(emailAddress)); Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_WRITE); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); Message[] messages = folder.getMessages(); if (messages != null && messages.length > 0) { for (Message message : messages) { String from = InternetAddress.toString(message.getFrom()); if (from != null) { System.out.println("發件人: " + MimeUtility.decodeText(from)); } String replayTo = InternetAddress.toString(message.getReplyTo()); if (replayTo != null) { System.out.println("回覆: " + MimeUtility.decodeText(replayTo)); } String to = InternetAddress.toString(message.getRecipients(RecipientType.TO)); System.out.println("收件人: " + MimeUtility.decodeText(to)); String subject = message.getSubject(); if (subject != null) { System.out.println("主題: " + MimeUtility.decodeText(subject)); } Date sendDate = message.getSentDate(); if (sendDate != null) { System.out.println("發送時間: " + sendDate); } System.out.println("肯定要刪除該郵件嗎?"); String answer = reader.readLine(); if ("yes".equalsIgnoreCase(answer)) { message.setFlag(Flags.Flag.DELETED, true); System.out.println("刪除消息成功"); } else { break; } } } folder.close(true); store.close(); } @Test public void testDeleteMails() throws Exception { deleteMails(); } }
/******************************************************************************** * Project Name [JavaEE_Components] * File Name [SearchingMails.java] * Creation Date [2015-01-01] * * Copyright© ge.y.yang@gmail.com All Rights Reserved * * Work hard, play harder, think big and keep fit ********************************************************************************/ package javamail.mail; import java.util.Calendar; import java.util.Date; import java.util.Properties; import javax.mail.Folder; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Store; import javax.mail.URLName; import javax.mail.search.AndTerm; import javax.mail.search.BodyTerm; import javax.mail.search.ComparisonTerm; import javax.mail.search.FromStringTerm; import javax.mail.search.IntegerComparisonTerm; import javax.mail.search.NotTerm; import javax.mail.search.OrTerm; import javax.mail.search.SearchTerm; import javax.mail.search.SentDateTerm; import javax.mail.search.SizeTerm; import javax.mail.search.SubjectTerm; import org.junit.Before; import org.junit.Test; import javamail.utils.MailConstants; import javamail.utils.PasswordUtils; /** * 搜索郵件 * * @author 不落的太陽(Sean Yang aka ShortPeace) * @version 1.0 * @since jdk 1.8 * */ public class SearchingMails { private static Properties properties = null; private static String emailAddress = "javamail_sns@sina.com"; private static URLName url; @Before public void init() { properties = new Properties(); properties.put("mail.pop3.auth", MailConstants.IS_AUTHORIZATION_NEED); properties.put("mail.debug", String.valueOf(MailConstants.IS_DEBUG_MOD_ENABLED)); url = new URLName(MailConstants.PROTOCAL_POP3, MailConstants.POP3_HOST_OF_SINA, Integer.parseInt(MailConstants.POP3_PORT_OF_SINA), null, emailAddress, PasswordUtils.readPassword(emailAddress)); } /** * 搜索郵件 * * @throws Exception */ public static void searchMails() throws Exception { // 建立Session對象並鏈接到指定的郵箱 Session session = Session.getInstance(properties); Store store = session.getStore(url); store.connect(emailAddress, PasswordUtils.readPassword(emailAddress)); // 得到收件箱 Folder folder = store.getFolder("INBOX"); // 以只讀權限打開收件箱, 還能夠配置爲Folder.READ_WRITE folder.open(Folder.READ_ONLY); // 獲得收件箱裏因此的郵件 Message[] messages = searchMails(folder); System.out.println("一共有郵件" + messages.length + "封"); } /** * 根據條件搜索郵件 * * @param folder * @return * @throws MessagingException */ @SuppressWarnings("unused") private static Message[] searchMails(Folder folder) throws MessagingException { // 搜索主題 String subject = "java"; SearchTerm subjectTerm = new SubjectTerm(subject); // 搜索發件人 String emailFrom = "18505106250@163.com"; SearchTerm fromTerm = new FromStringTerm(emailFrom); // 搜索內容 String content = "html"; SearchTerm bodyTerm = new BodyTerm(content); SearchTerm andTerm = new AndTerm(subjectTerm, fromTerm); SearchTerm notTerm = new NotTerm(bodyTerm); SearchTerm orTerm = new OrTerm(andTerm, notTerm); // 搜索週一到今天全部的郵件 Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); Date monday = calendar.getTime(); SearchTerm geTerm = new SentDateTerm(ComparisonTerm.GE, monday); SearchTerm leTerm = new SentDateTerm(ComparisonTerm.LE, new Date()); SearchTerm dateRangeTerm = new AndTerm(geTerm, leTerm); // 郵件大小 int size = 1024 * 100; // 100kb SearchTerm mailSizeTerm = new SizeTerm(IntegerComparisonTerm.GE, size); return folder.search(dateRangeTerm); } @Test public void testSearchMails() throws Exception { searchMails(); } }