現在我創建了一個代碼來檢索未讀電子郵件並閱讀其正文,然後我們可以存儲或執行我們想要的任何操作。從Gmail檢索UnRead電子郵件 - JavaMail API + IMAP
它是完全正常工作,但問題是,它只給我第一封郵件的身體和第二它給身體的HTML標籤。
我正在使用JavaMail API ...
我該怎麼辦?
在此先感謝。
最好的問候, 阿里
package pack1;
//import the necessary classes
import java.io.IOException;
import java.util.Properties;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;
public class InboxReader {
public static void main(String args[]) {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "mail", "pass");
System.out.println(store);
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
//Message messages[] = inbox.getMessages();
FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
Message messages[] = inbox.search(ft);
int i =0;
for(Message message:messages)
{
Multipart mp = (Multipart)messages[i].getContent();
Object p = mp.getBodyPart(i).getContent();
String q = p.toString();//object has the body content
System.out.println(q);//prints the body
System.out.println(messages[i].getSubject()+ " \n"+i);i++;
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
e.printStackTrace();
System.exit(2);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
輸出:
a
a
0
<div dir="ltr">b<br>
</div>
b
1
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 >= 2
at java.util.Vector.elementAt(Unknown Source)
at javax.mail.Multipart.getBodyPart(Multipart.java:156)
at javax.mail.internet.MimeMultipart.getBodyPart(MimeMultipart.java:258)
at pack1.InboxReader.main(InboxReader.java:39)
我不知道這樣的問題獲得+11而不是-20(並與13星號) – benchpresser 2018-01-22 14:39:24