java - 使用 javamail 通过 gmail 读取电子邮件时出现 ArrayOutOfBoundException

标签 java jakarta-mail netbeans-7

我正在尝试从我的 Gmail 帐户读取电子邮件。第一封电子邮件已成功读取,但对于第二封电子邮件,它给出了 ArrayOutOfBounds 异常。我的代码是

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();
        }

    }
}

错误

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)

第一封电子邮件,即电子邮件编号 1 已成功显示,但对于电子邮件编号 2 则出现异常。我的收件箱中共有 3 封邮件

最佳答案

实际导致异常的错误是:

BodyPart bp=mp.getBodyPart(i);

应该是:

BodyPart bp=mp.getBodyPart(0);

您应该将此部分放入 for 循环中,因为您可以有多个 body 部分。 检查documentation

修复此问题时的另一个错误将是:

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

Java中的数组是从零开始的,这意味着第一个元素的索引是0,最后一个元素的索引是array.length -1。您应该将其更改为:

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

关于java - 使用 javamail 通过 gmail 读取电子邮件时出现 ArrayOutOfBoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22835443/

相关文章:

java - 使用 Java 的 Netbeans : set all methods to static

java - Java中检查int变量是否上溢或下溢

java - 无法写入 JSON : failed to lazily initialize a collection of role: com. Managem.model.Region.pays,无法初始化代理 - 无 session

email - JavaMail 是否支持服务器推送?

java - 接收邮件并存储在jTable中

jboss7.x - 使用 Netbeans7 配置 JBoss 7 时出错

java - 剖析规范 Play Framework webapp 最佳实践

java - 从 super 对象创建子对象

android - java.lang.NoClassDefFoundError : javax. 激活.DataHandler

java - 通过Java进行邮件验证