POP3协议允许电子邮件客户端下载服务器上的邮件, 但是在客户端的操作[如移动邮件, 标记已读等), 不会反馈到服务器上
IMAP协议提供WebMail与电子邮件客户端之间的双向通信, 客户端的操作都会同步反应到服务器上, 对邮件进行的操作, 服务器上的邮件也会做相应的动作, 比如在客户端收取了邮箱中的3封邮件, 并将其中一封标记为已读, 将另外两封标记为删除, 这些操作会即时反馈到服务器上
两种协议相比, IMAP协议更为便捷和可靠, POP3容易丢失邮件或多次下载相同的邮件, 但IMAP协议通过邮件客户端, 与WebMail之间的双向同步功能很好地避免了这些问题
/******************************************************************************** * Project Name [JavaEE_Components] * File Name [CheckingMailsByPop3.java] * Creation Date [2015-01-01] * * Copyright© [email protected] 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 = "[email protected]"; @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© [email protected] 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 = "[email protected]"; @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, 增加相应的解析方法
由于超出博文限制, 下一篇会单独列出
/******************************************************************************** * Project Name [JavaEE_Components] * File Name [ReplyingMails.java] * Creation Date [2015-01-01] * * Copyright© [email protected] 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 = "[email protected]"; @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© [email protected] 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 = "[email protected]"; @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© [email protected] 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 = "[email protected]"; @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© [email protected] 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 = "[email protected]"; 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 = "[email protected]"; 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(); } }