Skip to content

Instantly share code, notes, and snippets.

@winterbe
Created July 9, 2013 15:39
Show Gist options
  • Save winterbe/5958387 to your computer and use it in GitHub Desktop.
Save winterbe/5958387 to your computer and use it in GitHub Desktop.
Reading the Body Text of a javax.mail.Message
private boolean textIsHtml = false;
/**
* Return the primary text content of the message.
*/
private String getText(Part p) throws MessagingException, IOException {
if (p.isMimeType("text/*")) {
String s = (String)p.getContent();
textIsHtml = p.isMimeType("text/html");
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;
}
@Nk127
Copy link

Nk127 commented Feb 2, 2022

thanks man

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment