import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeUtility; import java.io.UnsupportedEncodingException; import java.security.Security; import java.util.Properties; /** * 用于收取Gmail邮件 * * @author wuhua */ public class GmailFetch { public static void main(String argv[]) throws Exception { System.out.println("开始读取邮件"); Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); // Get a Properties object Properties props = System.getProperties(); props.setProperty("mail.store.protocol", "imaps"); // 如下步骤跟通常的JavaMail操做相同 Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); //把这里的邮箱帐号密码替换成你本身的 store.connect("imap.gmail.com", "yourgmail@address", "yourpassword"); System.out.println(store); Folder[] f = store.getDefaultFolder().list(); for(Folder fd:f) System.out.println(">> "+fd.getName()); Folder inbox = null; try { inbox = store.getFolder("Debug"); inbox.open(Folder.READ_ONLY); FetchProfile profile = new FetchProfile(); profile.add(FetchProfile.Item.ENVELOPE); Message[] messages = inbox.getMessages(); inbox.fetch(messages, profile); System.out.println("收件箱的邮件数:" + messages.length); for (int i = 0; i < messages.length; i++) { // 邮件发送者 String from = decodeText(messages[i].getFrom()[0].toString()); InternetAddress ia = new InternetAddress(from); // logger.debug("发信人:" + ia.getPersonal() + '(' // + ia.getAddress() + ')'); // 邮件标题 System.out.println(messages[i].getSubject()); // 邮件大小 // logger.debug("邮件大小:" + messages[i].getSize()); // 邮件发送时间 // logger.debug("发送日期:" + messages[i].getSentDate()); } } finally { try { inbox.close(false); } catch (Exception e) { } try { store.close(); } catch (Exception e) { } } System.out.println("读取邮件完毕"); } protected static String decodeText(String text) throws UnsupportedEncodingException { if (text == null) return null; if (text.startsWith("=?GB") || text.startsWith("=?gb")) text = MimeUtility.decodeText(text); else text = new String(text.getBytes("ISO8859_1")); return text; } }
我最开始经过pop3的方式获取email,可是pop3只能收取inbox的email.能够参考这里,要收取其余label的邮件,必须采用imap的方式.html
采用IMAP收取email,可能须要先把gmail邮箱设置成 enable IMAP 'Setting--->Forwarding and POP/IMAP--->Enable IMAP'就能够了.java
gmail的平常使用 若是我想把过滤出的email所有变成已读或删除,但默认只能显示20行.其实过滤,select all以后,在上面会提示"是否须要用于全部的1234个会话?",选择这个,就能够给全部的邮件执行批量操做了(虽然只能显示一部分.)浏览器
gmail的feed 登录gmail后,再浏览器中输入 https://mail.google.com/mail/feed/atom/yourLabelName, 最后"yourLabelName"替换成你想看的label,就能够在浏览器中看到前20条email的摘要了. 参考这里session
使用的代码主要参考这里,不过它是pop3的,局限性太多,建议你们都采用IMAP的方式ide
1.关于POP3和IMAP的区别,请参考这里fetch