Вопрос

I am trying to read emails from my gmail account. The first email is read successfully but for 2nd email it gives an ArrayOutOfBounds exception. My code is

package sendemail;
import javax.mail.*;
import java.net.*;
import java.util.*;
import javax.swing.JOptionPane;
/**
 *
 * @author kunal
 */
public class Test {
    public static void main(String args[])
    {
        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", "myaccount@gmail.com", "mypassword");
            Folder inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_ONLY);
            Message[] messages = inbox.getMessages(); 

   for (int i = 0; i <=messages.length; i++) {  
    Message message = messages[i];
    Multipart mp=(Multipart)message.getContent();
    BodyPart bp=mp.getBodyPart(i);
    System.out.println("---------------------------------");  
    System.out.println("Email Number " + (i + 1));  
    System.out.println("Subject: " + message.getSubject());  
    System.out.println("From: " + message.getFrom()[0]);  
    System.out.println("Text: " + bp.getContent());  
   }
        } catch (Exception mex) {
            mex.printStackTrace();
        }

    }
}

Error

Email Number 1
Subject: Three tips to get the most out of Gmail
From: Gmail Team <mail-noreply@google.com>
Text:  Three tips to get the most out of Gmail
[image: Google]

Hi Kunal

Tips to get the most out of Gmail

[image: Contacts]
Bring your contacts and mail into Gmail

On your computer, you can copy your contacts and emails from your old email
account to make the transition to Gmail even better. Learn
how<https://support.google.com/mail/answer/164640?hl=en&ref_topic=1669014>
.
[image: Search]
Find what you need fast

With the power of Google Search right in your inbox, it's easy to sort your
email. Find what you're looking for with predictions based on email
content, past searches and contacts.
[image: Search]
Much more than email

You can send text messages and make video calls with
Hangouts<https://www.google.com/intl/en/hangouts/>right from Gmail. To
use this feature on mobile, download the Hangouts app
for Android<https://play.google.com/store/apps/details?id=com.google.android.talk&hl=en>and
Apple <https://itunes.apple.com/en/app/hangouts/id643496868?mt=8> devices.


[image: Gmail icon]Happy emailing,
The Gmail Team
 © 2014 Google Inc. 1600 Amphitheatre Parkway, Mountain View, CA 94043

---------------------------------
Email Number 2
Subject: The best of Gmail, wherever you are
From: Gmail Team <mail-noreply@google.com>
Text: <!DOCTYPE html>
<html><head><meta http-equiv="content-type" content="text/html;charset=UTF-8" /><title>The best of Gmail, wherever you are</title></head><body style="background-color:#e5e5e5; margin:20px 0;"><br /><div style="margin:2%;"><div style="direction:ltr; text-align:left; font-family:'Open sans','Arial',sans-serif; color:#444; background-color:white; padding:1.5em; border-radius:1em; box-shadow:1px -5px 8px 2px #bbb; max-width:580px; margin:2% auto 0 auto;"><table style="background:white;width:100%"><tr><td><div style="width:90px; height:54px; margin:10px auto;"><img src="https://services.google.com/fh/files/emails/google_logo_flat_90_color.png" alt="Google" width="90" height="34"/></div><div style="float:right; padding-top:2em;"><img src="https://ssl.gstatic.com/accounts/services/mail/msa/welcome_nexus.png" alt="Nexus 4 with Gmail" style="border:0; margin-right:10px;" width="155" height="242"/></div><div style="width:90%; padding-bottom:10px; padding-left:15px"><p><img alt="" src="https://ssl.gstatic.com/accounts/services/mail/msa/gmail_icon_small.png" style="display:block; float:left; margin-top:4px; margin-right:5px;"/><span style="font-family:'Open sans','Arial',sans-serif; font-weight:bold; font-size:small; line-height:1.4em">Hi Kunal</span></p><p><span style="font-family:'Open sans','Arial',sans-serif; font-size:2.08em;"><br/>Get the official Gmail app</span><br/></p></div><p></p><div style="padding-left:15px"><p style="size:small; line-height:1.4em;">The best features of Gmail are only available on your phone and tablet with the official Gmail app. Download the app or go to <a href="https://www.gmail.com/" target="_blank" style="text-decoration:none; color:#15C">gmail.com</a> on your computer or mobile device to get started.</p><p style="line-height:2em; margin-right:170px;"><a href="https://play.google.com/store/apps/details?id=com.google.android.gm" style="text-decoration:none"><img alt="Google Play" width="127" height="44" src="https://ssl.gstatic.com/accounts/services/mail/buttons/google_play_en.png" style="border:0" /></a>&nbsp;&nbsp;<a href="https://itunes.apple.com/en/app/gmail/id422689480?mt=8" style="text-decoration:none;"><img alt="App Store" width="144" height="43" src="https://ssl.gstatic.com/accounts/services/mail/buttons/apple_store_en.png" style="border:0" /></a></p></div><br/><br/>
<div style="clear:both; padding-left:13px; height:6.8em;"><table style="width:100%; border-collapse:collapse; border:0"><tr><td style="width:68px"><img alt='Gmail icon' width="49" height="37" src="http://ssl.gstatic.com/accounts/services/mail/msa/gmail_icon_large.png" style="display:block;"/></td><td style="align:left; font-family:'Open sans','Arial',sans-serif; vertical-align:bottom"><span style="font-size:small">Happy emailing,<br/></span><span style="font-size:x-large; line-height:1">The Gmail Team</span></td></tr></table></div>
</td></tr></table></div>
<div style="direction:ltr;color:#777; font-size:0.8em; border-radius:1em; padding:1em; margin:0 auto 4% auto; font-family:'Arial','Helvetica',sans-serif; text-align:center;">© 2014 Google Inc. 1600 Amphitheatre Parkway, Mountain View, CA 94043<br/></div></div></body></html>

java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
    at java.util.Vector.elementAt(Vector.java:470)
    at javax.mail.Multipart.getBodyPart(Multipart.java:156)
    at javax.mail.internet.MimeMultipart.getBodyPart(MimeMultipart.java:258)
    at sendemail.Test.main(Test.java:32)
BUILD SUCCESSFUL (total time: 10 seconds)

The first email i.e Email number 1 is displayed successfully but for Email number 2 it gives an exception. There are total 3 mails in my inbox

Это было полезно?

Решение

Error which actually causes exception is:

BodyPart bp=mp.getBodyPart(i);

It should be:

BodyPart bp=mp.getBodyPart(0);

You should put this part in a for loop, since you can have multiple body parts. Check the documentation

Another error when you fix this will be:

for (int i = 0; i <= messages.length; i++)

Arrays in Java are zero based, which means that index of the first element is 0 and the index of the last element is array.length -1. You should change it to:

for (int i = 0; i < messages.length; i++)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top