计算Gmail INBOX中的电子邮件数量

这是用于计算gmail邮箱中邮件数量的代码。

 Properties props = new Properties(); props.put("mail.pop3.host" , "pop.gmail.com"); props.put("mail.pop3.user" , "username"); props.put("mail.pop3.socketFactory" , 995 ); props.put("mail.pop3.socketFactory.class" , "javax.net.ssl.SSLSocketFactory" ); props.put("mail.pop3.port" , 995); Session session = Session.getDefaultInstance(props , new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( "username" , "password"); } }); try { Store store = session.getStore("pop3"); store.connect("pop.gmail.com" , "username" , "password"); Folder fldr = store.getFolder("INBOX"); fldr.open(Folder.HOLDS_MESSAGES); int count = fldr.getMessageCount(); System.out.println(count); } catch(Exception exc) { System.out.println(exc + " error"); } 

我得到的计数等于7但我应该得到3因为我在收件箱中只有3条消息。

在GMAIL POP3设置中,您应该仅为当前时刻收到的电子邮件启用POP访问,这是标准的GMAIL行为。

启用POP后,除垃圾邮件,已删除垃圾邮件和聊天记录外,所有邮件都会下载到您的客户端。 如果您不希望从Web界面发送的邮件下载到您的邮件客户端的收件箱,我们建议您在客户端中创建一个filter。 您可能需要与邮件客户端的客户服务部门联系,以获取有关如何对下载的邮件进行分类的说明。

请参阅GMAIL疑难解答文章

GMAIL中的AFAIK选择性同步仅适用于IMAP协议。

为此使用IMAP协议。

 Properties props = new Properties(); props.put("mail.imap.host" , "imap.gmail.com"); props.put("mail.imap.user" , "username"); props.put("mail.imap.socketFactory" , 993 ); props.put("mail.imap.socketFactory.class" , "javax.net.ssl.SSLSocketFactory" ); props.put("mail.imap.port" , 993); Session session = Session.getDefaultInstance(props , new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication( "username" , "password"); } }); try { Store store = session.getStore("imap"); store.connect("imap.gmail.com" , "username" , "password"); Folder fldr = store.getFolder("Inbox"); fldr.open(Folder.HOLDS_MESSAGES); int count = fldr.getMessageCount(); System.out.println(count); } catch(Exception exc) { System.out.println(exc + "error"); } 

以下是从收件箱中阅读电子邮件的示例。

http://bharatonjava.wordpress.com/2012/09/15/read-emails-form-inbox/

这是代码片段

 public static void main(String[] args){ Properties props = new Properties(); try { props.load(new FileInputStream(new File("settings.properties"))); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } Session session = Session.getDefaultInstance(props, null); Store store = session.getStore("imaps"); store.connect("smtp.gmail.com", "yourEmailId@gmail.com", "put your password here"); Folder inbox = store.getFolder("inbox"); inbox.open(Folder.READ_WRITE); // Folder.READ_ONLY int messageCount = inbox.getMessageCount(); System.out.println("Total Messages" + messageCount); } 

您必须将您的电子邮件设置保存在名为settings.properties的属性文件中,如下所示。

 mail.smtp.host=smtp.gmail.com mail.smtp.socketFactory.port=465 mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory mail.smtp.auth=true mail.smtp.port=465