我正在使用javax.mail开发客户端邮件以读取邮箱中的邮件:

Properties properties = System.getProperties();
properties.setProperty("mail.store.protocol", "imap");
try {
    Session session = Session.getDefaultInstance(properties, null);
    Store store = session.getStore("pop3");//create store instance
    store.connect("pop3.domain.it", "mail.it", "*****");
    Folder inbox = store.getFolder("inbox");
    FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
    inbox.open(Folder.READ_ONLY);//set access type of Inbox
    Message messages[] = inbox.search(ft);
    String mail,sub,bodyText="";
    Object body;
    for(Message message:messages) {
        mail = message.getFrom()[0].toString();
        sub = message.getSubject();
        body = message.getContent();
        //bodyText = body.....
    }
} catch (Exception e) {
    System.out.println(e);
}

我知道getContent()方法返回一个对象,因为内容可能是StringMimeMultiPartSharedByteArrayInputstream和其他(我认为)...有没有办法让消息始终位于消息正文中?谢谢!!

最佳答案

这个答案扩展了yurin's answer。他提出的问题是MimeMultipart的内容本身可能是另一个MimeMultipart。在这种情况下,下面的getTextFromMimeMultipart()方法将在内容上重复出现,直到完全解析了邮件正文为止。

private String getTextFromMessage(Message message) throws MessagingException, IOException {
    String result = "";
    if (message.isMimeType("text/plain")) {
        result = message.getContent().toString();
    } else if (message.isMimeType("multipart/*")) {
        MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
        result = getTextFromMimeMultipart(mimeMultipart);
    }
    return result;
}

private String getTextFromMimeMultipart(
        MimeMultipart mimeMultipart)  throws MessagingException, IOException{
    String result = "";
    int count = mimeMultipart.getCount();
    for (int i = 0; i < count; i++) {
        BodyPart bodyPart = mimeMultipart.getBodyPart(i);
        if (bodyPart.isMimeType("text/plain")) {
            result = result + "\n" + bodyPart.getContent();
            break; // without break same text appears twice in my tests
        } else if (bodyPart.isMimeType("text/html")) {
            String html = (String) bodyPart.getContent();
            result = result + "\n" + org.jsoup.Jsoup.parse(html).text();
        } else if (bodyPart.getContent() instanceof MimeMultipart){
            result = result + getTextFromMimeMultipart((MimeMultipart)bodyPart.getContent());
        }
    }
    return result;
}

08-17 16:27