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++)