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