1

我正在尝试使用 Javamail api 在 Gmail 中获取最后发送的邮件。这是代码 -

Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imap");

try{
    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imap");
    store.connect(mailbox, mailId, passwod);

    sent  = store.getFolder("[Gmail]/Sent Mail");
    int totalSentMails = sent.getMessageCount();

    sent.open(Folder.READ_ONLY);


    Message sentmesage = sent.getMessage(totalSentMails);
}
catch (NoSuchProviderException e){
      e.printStackTrace();
      System.exit(1);
}

由于 getMessage 计数返回的数字远大于实际邮件,因此我得到了 IndexOutOfBoundsException。

如何使用 javamail api 从 Gmail 中获取确切数量的已发送邮件?我得到的错误是 -

java.lang.IndexOutOfBoundsException: 1986 > 1970

1986 是上面获取的 totalSentMails 的值,1970 是实际发送的邮件数

4

1 回答 1

1

**

使用此代码阅读 gmail 已发送邮件文件夹、草稿、重要、已加星标、垃圾邮件、垃圾箱、收件箱、所有邮件

**

    Properties props = new Properties();

    props.setProperty("mail.store.protocol", "imaps");

    try {
        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect("imap.gmail.com", "xxxxxxx@gmail.com", "gmailpassword");
        Folder[] folderList = store.getFolder("[Gmail]").list();
        for (int i = 0; i < folderList.length; i++) {
            System.out.println(folderList[i].getFullName());
        }
        Folder inbox = store.getFolder("[Gmail]/Sent Mail");
        inbox.open(Folder.READ_ONLY);
        Message msg = inbox.getMessage(inbox.getMessageCount());
        Address[] in = msg.getFrom();
        for (Address address : in) {
            System.out.println("FROM:" + address.toString());
        }
        Multipart mp = (Multipart) msg.getContent();
        BodyPart bp = mp.getBodyPart(0);
        System.out.println("Bcc User NAme :"+InternetAddress.toString(msg.getRecipients(Message.RecipientType.BCC)));
        System.out.println("SENT DATE:" + msg.getSentDate());
        System.out.println("SUBJECT:" + msg.getSubject());
        System.out.println("CONTENT:" + bp.getContent());
    } catch (Exception mex) {
        mex.printStackTrace();
    }

这段代码工作得很好,伙计们..享受:)

于 2014-01-08T13:12:27.190 回答