无法使用Java阅读电子邮件内容

时间:2015-08-14 07:35:21

标签: java email

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", "xxx", "xxx");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message[] messages = inbox.getMessages();
for (int i = messages.length;i>=0; i--) {
Message message =messages[i];

System.out.println("Text: " + message.getContent().toString());
}

我能够阅读电子邮件,并且我正在尝试为每封电子邮件获取电子邮件内容。但是getContent方法返回垃圾值,例如:(文本:javax.mail.internet.MimeMultipart@17ff24f)。 如何获得完整的电子邮件内容。请帮忙。

1 个答案:

答案 0 :(得分:1)

message.getContent()的调用不会返回“垃圾值”,只会返回无法直接转换为String值的内容。

这是因为它是类MimeMultipart的对象。这意味着您正在阅读的电子邮件包含多个“部分”。您可以将message.getContent()的结果向下转换为MimeMultipart变量并对其进行分析:

MimeMultipart multipart = (MimeMultipart) message.getContent();
System.out.println("This message consists of " + multipart.getCount() + " parts");
for (int i = 0; i < multipart.getCount(); i++) {
    // Note we're downcasting here, MimeBodyPart is the only subclass
    // of BodyPart available in the Java EE spec.
    MimeBodyPart bodyPart = (MimeBodyPart) multipart.getBodyPart(i); 

    System.out.println("Part " + i + " has type " + bodyPart.getContentType());
    System.out.println("Part " + i " + has filename " + bodyPart.getFileName()); // if it was an attachment
    // So on, so forth.
}

有关如何分析邮件部分的详细信息,请参阅Javadoc of MimeBodyPart