【问题标题】:Unable to read email content using Java无法使用 Java 读取电子邮件内容
【发布时间】:2015-11-07 09:24:56
【问题描述】:
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 方法返回垃圾值,例如:(Text:javax.mail.internet.MimeMultipart@17ff24f)。 如何获得完整的电子邮件内容。请帮忙。

【问题讨论】:

标签: java email


【解决方案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

【讨论】:

    猜你喜欢
    • 2018-04-08
    • 2015-11-20
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多