Search code examples
jakarta-mailmimemime-message

MimeMessage email get reply body without the previous Correspondence


In my server I'm receiving emails constantly from gmail..

I receive them as MimeMessage type.

What I'm doing so far is extracting the body text with the method:

private String getText(Part p) throws MessagingException, IOException {
    if (p.isMimeType("text/*")) {
      String s = (String) p.getContent();
      return s;
  }

if (p.isMimeType("multipart/alternative")) {
    // prefer html text over plain text
    Multipart mp = (Multipart) p.getContent();
    String text = null;
    for (int i = 0; i < mp.getCount(); i++) {
    Part bp = mp.getBodyPart(i);
    if (bp.isMimeType("text/plain")) {
        if (text == null)
        text = getText(bp);
        continue;
    } else if (bp.isMimeType("text/html")) {
        String s = getText(bp);
        if (s != null)
        return s;
    } else {
        return getText(bp);
    }
    }
    return text;
} else if (p.isMimeType("multipart/*")) {
    Multipart mp = (Multipart) p.getContent();
    for (int i = 0; i < mp.getCount(); i++) {
    String s = getText(mp.getBodyPart(i));
    if (s != null)
        return s;
    }
}

return null;
}

My problem right now is based on emails i get that are "in reply to" a previous email. When i extract these emails for their text i receive the "X wrote in Y ..." and then all the previous correspondence. How do i get only the new response text? (without the previous correspondence)?

thanks.


Solution

  • I'm sure this has been discussed previously on stackoverflow but I'll let you do the searching...

    Simple answer: There's no standard way to do this. Different mailers choose different techniques for embedding the text of the original message in a reply message. There are common conventions, and you can write heuristics to recognize those conventions, but because they're heuristics they will fail sometimes. JavaMail has nothing to help you here; this is just a string processing problem.