Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

May be a liter late for Urbanleg, but it could help someone else. This code make the job for me. Just like Bill said, is a work with Strings. The email address of receiver be always in the reply part, use it like refernce.

public static String cleanReplyFromBodyEmail(String body, String emailAdress){
    if (!body.contains(emailAdress))
        return body;

    String bodyWoReply = body.split(emailAdress)[0];
    String[] bodyLines = bodyWoReply.split("\\n");
    if(bodyLines.length <= 1)
        bodyLines = bodyWoReply.split("\\r");
    String finalBody = "";
    for (int i=0; i < (bodyLines.length - 1); i++){
        finalBody += bodyLines[i] + "\n";
    }
    return finalBody;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top