修改JavaMail代码以下载最近10条消息

时间:2015-07-15 00:43:11

标签: java javamail

我使用以下代码从Gmail下载邮件。

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;

import org.openqa.selenium.WebDriver;

public class MailReader {

    WebDriver driver;
    Folder inbox;
    String m;

    String gmailID = "xyz@gmail.com";
    String gmailPass = "xyz";
    String storeMessage;

    public MailReader()
    {

    }

    public String readMail() {
        System.out.println("Inside readMail()...");
        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, gmailID,
                    gmailPass);

            /* 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

            {

                m = 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);
        }
        return m;

    }

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

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

            s = printEnvelope(msgs[i]);
        }
        return s;

    }

    public String 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);

        return(getContent(message));

    }





    public String getContent(Message msg)

    {
        try {
            String contentType = msg.getContentType();
            System.out.println("Content Type : " + contentType);
            Multipart mp = (Multipart) msg.getContent();

            BodyPart bp = mp.getBodyPart(0);

            int count = mp.getCount();

            for (int i = 0; i < count; i++) {
                String s = getText(mp.getBodyPart(i));
                if(i == 1) {
                    return s;
                }
                //dumpPart(mp.getBodyPar((i));
                }
        } catch (Exception ex) {
            System.out.println("Exception arise at get Content");
            ex.printStackTrace();
        }
        return m;
    }

/*
    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);


        }
    }*/

     boolean textIsHtml = false;

    /**
     * Return the primary text content of the message.
     */
    public String getText(Part p) throws
                MessagingException, IOException {
        if (p.isMimeType("text/*")) {
            String s = (String)p.getContent();
            textIsHtml = p.isMimeType("text/html");
            return s;
        }

        if (p.isMimeType("multipart/alternative")) {
            // prefer html text over plain text
            Multipart mp = (Multipart)p.getContent();
            String text = null;
            for (int i = 0; i < mp.getCount(); i++) {
                Part bp = mp.getBodyPart(i);
                if (bp.isMimeType("text/plain")) {
                    if (text == null)
                        text = getText(bp);
                    continue;
                } else if (bp.isMimeType("text/html")) {
                    String s = getText(bp);
                    if (s != null)
                        return s;
                } else {
                    return getText(bp);
                }
            }
            return text;
        } else if (p.isMimeType("multipart/*")) {
            Multipart mp = (Multipart)p.getContent();
            for (int i = 0; i < mp.getCount(); i++) {
                String s = getText(mp.getBodyPart(i));
                if (s != null)
                    return s;
            }
        }

        return null;
    }

}

我想修改代码,以便:

  1. 仅下载最近10条未读消息
  2. 仅下载从特定地址发送的邮件(例如,仅发送自myemail@example.com发送的邮件
  3. 如何做到这一点?

    谢谢!

1 个答案:

答案 0 :(得分:1)

最近10条消息是INBOX中的最后10条消息。

但其中一些可以被阅读,其中一些可能被删除。要查找10条最近未读的消息,您需要使用FlagTerm来搜索SEEN标志为false的消息。您可能希望使用AndTerm来查找DELETED标志也为假的消息。

请注意,Folder.search并非下载任何消息,它只会告诉您哪些消息匹配。然后,您可以查看这些消息的最后10条,并执行您需要执行的任何操作,以便下载&#34;它们。

希望这足以让你开始。如果您仍然无法使用它,请向我们展示您正在使用的代码以及您将获得的结果。