使用带有POP3协议的javamail检索所有未读电子邮件 [英] Retrieving all unread emails using javamail with POP3 protocol

查看:129
本文介绍了使用带有POP3协议的javamail检索所有未读电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问我的Gmail帐户并从中检索所有未读电子邮件的信息。

I am trying to access my gmail account and retrieve the information of all unread emails from that.

我在引用许多链接后编写了我的代码。我给出了一些链接供参考。

I have written my code after referring many links. I am giving a few links for reference.


发送&使用Java通过GMail帐户接收电子邮件

使用JavaMailAPI接收邮件的Java代码

要测试我的代码,我创建了一个Gmail帐户。所以我收到了来自Gmail的4封邮件。
我在检查邮件数量后运行我的应用程序。这显示了正确的结果。 4封未读邮件。
显示所有信息(例如日期,发件人,内容,主题等)。

To test my code, I created one Gmail account. So I received 4 messages in that from Gmail. I run my application after checking number of mails. That showed correct result. 4 unread mails. All the infomation was being displayed (e.g. date, sender, content, subject, etc.)

然后我登录到我的新帐户,阅读其中一个电子邮件并重新运行我的应用程序。
现在未读消息的数量应为3,但它显示未读消息数:0

Then I logged in to my new account, read one of the emails and rerun my application. Now the count of unread message should have been 3, but it displays "No. of Unread Messages : 0"

我在这里复制代码。

public class MailReader

{

    Folder inbox;

    // Constructor of the calss.

    public MailReader() {
        System.out.println("Inside MailReader()...");
        final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        /* Set the mail properties */

        Properties props = System.getProperties();
        // Set manual Properties
        props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.pop3.socketFactory.fallback", "false");
        props.setProperty("mail.pop3.port", "995");
        props.setProperty("mail.pop3.socketFactory.port", "995");
        props.put("mail.pop3.host", "pop.gmail.com");

        try

        {

            /* Create the session and get the store for read the mail. */

            Session session = Session.getDefaultInstance(
                    System.getProperties(), null);

            Store store = session.getStore("pop3");

            store.connect("pop.gmail.com", 995, "abc@gmail.com",
                    "paasword");

            /* Mention the folder name which you want to read. */

            // inbox = store.getDefaultFolder();
            // inbox = inbox.getFolder("INBOX");
            inbox = store.getFolder("INBOX");

            /* Open the inbox using store. */

            inbox.open(Folder.READ_ONLY);

            /* Get the messages which is unread in the Inbox */

            Message messages[] = inbox.search(new FlagTerm(new Flags(
                    Flags.Flag.SEEN), false));
            System.out.println("No. of Unread Messages : " + messages.length);

            /* Use a suitable FetchProfile */
            FetchProfile fp = new FetchProfile();
            fp.add(FetchProfile.Item.ENVELOPE);

            fp.add(FetchProfile.Item.CONTENT_INFO);

            inbox.fetch(messages, fp);

            try

            {

                printAllMessages(messages);

                inbox.close(true);
                store.close();

            }

            catch (Exception ex)

            {
                System.out.println("Exception arise at the time of read mail");

                ex.printStackTrace();

            }

        }

        catch (MessagingException e)
        {
            System.out.println("Exception while connecting to server: "
                    + e.getLocalizedMessage());
            e.printStackTrace();
            System.exit(2);
        }

    }

    public void printAllMessages(Message[] msgs) throws Exception
    {
        for (int i = 0; i < msgs.length; i++)
        {

            System.out.println("MESSAGE #" + (i + 1) + ":");

            printEnvelope(msgs[i]);
        }

    }

    public void printEnvelope(Message message) throws Exception

    {

        Address[] a;

        // FROM

        if ((a = message.getFrom()) != null) {
            for (int j = 0; j < a.length; j++) {
                System.out.println("FROM: " + a[j].toString());
            }
        }
        // TO
        if ((a = message.getRecipients(Message.RecipientType.TO)) != null) {
            for (int j = 0; j < a.length; j++) {
                System.out.println("TO: " + a[j].toString());
            }
        }
        String subject = message.getSubject();

        Date receivedDate = message.getReceivedDate();
        Date sentDate = message.getSentDate(); // receivedDate is returning
                                                // null. So used getSentDate()

        String content = message.getContent().toString();
        System.out.println("Subject : " + subject);
        if (receivedDate != null) {
            System.out.println("Received Date : " + receivedDate.toString());
        }
        System.out.println("Sent Date : " + sentDate.toString());
        System.out.println("Content : " + content);

        getContent(message);

    }

    public void getContent(Message msg)

    {
        try {
            String contentType = msg.getContentType();
            System.out.println("Content Type : " + contentType);
            Multipart mp = (Multipart) msg.getContent();
            int count = mp.getCount();
            for (int i = 0; i < count; i++) {
                dumpPart(mp.getBodyPart(i));
            }
        } catch (Exception ex) {
            System.out.println("Exception arise at get Content");
            ex.printStackTrace();
        }
    }

    public void dumpPart(Part p) throws Exception {
        // Dump input stream ..
        InputStream is = p.getInputStream();
        // If "is" is not already buffered, wrap a BufferedInputStream
        // around it.
        if (!(is instanceof BufferedInputStream)) {
            is = new BufferedInputStream(is);
        }
        int c;
        System.out.println("Message : ");
        while ((c = is.read()) != -1) {
            System.out.write(c);
        }
    }

    public static void main(String args[]) {
        new MailReader();
    }
}

我在谷歌搜索,但我发现你应该使用Flags.Flag.SEEN读取未读电子邮件。
但是在我的情况下没有显示正确的结果。

I searched on google, but I found that you should use Flags.Flag.SEEN to read unread emails. But thats not showing correct results in my case.

有人可以指出我可能在做错的地方吗?

Can someone point out where I might be doing some mistake?

如果您需要完整的代码,我可以编辑我的帖子。

If you need whole code, I can edit my post.

注意:我编辑了我的问题以包含整个代码而不是我之前发布的代码段。

Note: I edited my question to include whole code instead of snippet I had posted earlier.

推荐答案

您的代码应该有效。如果你想要的只是计数,你也可以使用Folder.getUnreadMessageCount()方法。

Your code should work. You can also use the Folder.getUnreadMessageCount() method if all you want is the count.

JavaMail只能告诉你Gmail的用途。也许Gmail认为所有这些消息都已被阅读?也许Gmail网络界面正在标记这些消息?也许你有另一个应用程序监视文件夹中的新消息?

JavaMail can only tell you what Gmail tells it. Perhaps Gmail thinks that all those messages have been read? Perhaps the Gmail web interface is marking those messages read? Perhaps you have another application monitoring the folder for new messages?

尝试用JavaMail读取未读消息并查看计数是否发生变化。

Try reading an unread message with JavaMail and see if the count changes.

您可能会发现打开会话调试很有用,这样您就可以看到Gmail正在返回的实际IMAP响应;请参阅 JavaMail常见问题解答

You might find it useful to turn on session debugging so you can see the actual IMAP responses that Gmail is returning; see the JavaMail FAQ.

这篇关于使用带有POP3协议的javamail检索所有未读电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆