Skip to content
Advertisement

How to read text inside body of mail using javax.mail

i’m developing a client mail using javax.mail to read mail inside mail box:

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

I know that the method getContent() returns an object cause the content could be a String, a MimeMultiPart, a SharedByteArrayInputstream and other ( i think )… Is there a way to get always the text inside body of message? Thanks!!

Advertisement

Answer

This answer extends yurin’s answer. The issue he brought up was that the content of a MimeMultipart may itself be another MimeMultipart. The getTextFromMimeMultipart() method below recurses in such cases on the content until the message body has been fully parsed.

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

private String getTextFromMimeMultipart(
        MimeMultipart mimeMultipart)  throws MessagingException, IOException{
    String result = "";
    for (int i = 0; i < mimeMultipart.getCount(); i++) {
        BodyPart bodyPart = mimeMultipart.getBodyPart(i);
        if (bodyPart.isMimeType("text/plain")) {
            return result + "n" + bodyPart.getContent(); // without return, same text appears twice in my tests
        } 
        result += this.parseBodyPart(bodyPart);
    }
    return result;
}

private String parseBodyPart(BodyPart bodyPart) throws MessagingException, IOException { 
    if (bodyPart.isMimeType("text/html")) {
        return "n" + org.jsoup.Jsoup
            .parse(bodyPart.getContent().toString())
            .text();
    } 
    if (bodyPart.getContent() instanceof MimeMultipart){
        return getTextFromMimeMultipart((MimeMultipart)bodyPart.getContent());
    }

    return "";
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement