The emails that are being recieved by my apex-email-service do not have plainTextBodies. Is there a way to convert HTML to PlaintextBody in apex?

  • Originally I was trying to auto-forward mail in plainText through gmail. Unfortunately they don't support this feature. If you manually forward the email through gmail, you can convert it to plain text. But I am trying to create a system that doesn't require manual labor. @AdrianLarson Sep 17, 2015 at 19:53
  • You could try just replacing all tags with the empty string. Sample regex: <\/?\w*\b[^>]*>.
    – Adrian Larson
    Sep 17, 2015 at 20:01
  • So this would replace all tags and their contents. Would that really cause a complete conversion from html to plaintext? I know there may also be some CSS in there...but besides that, is this foolproof? @AdrianLarson Sep 17, 2015 at 20:25
  • Far from foolproof. You could or in a search for <style> tags and include their contents. For example: <style>[^<]*<\/style>|<\/?\w*\b[^>]*>.
    – Adrian Larson
    Sep 17, 2015 at 20:33
  • 1
    You should post that as a separate question.
    – Adrian Larson
    Sep 18, 2015 at 17:44

2 Answers 2


I think rather than using any RegEx, you can just use a built in String method: stripHtmlTags.

Salesforce String Class

So it would look like:

String plainText = htmlBody.stripHtmlTags();
  • With the following caveat: The stripHtmlTags function does not recursively strip tags; therefore, tags may still exist in the returned string. Do not use the stripHtmlTags function to sanitize input for inclusion as a raw HTML page. The unescaped output is not considered safe to include in an HTML document. The function will be deprecated in a future release. Dec 2, 2021 at 12:11

Just realized that I basically answered this in the comments, so it might make sense to post as a proper answer.

I would just try to replace all tags with the empty string. Example:

Pattern tagPattern = Pattern.compile('<\/?\w*\b[^>]*>');
String plainTextBody = tagPattern.matcher(htmlBody).replaceAll('');
  • why not just use .stripHTMLTags? developer.salesforce.com/docs/atlas.en-us.apexcode.meta/… Mar 31, 2017 at 20:38
  • 2
    @techbusinessman Because I wasn't aware of that function at the time. This post is over a year old now.
    – Adrian Larson
    Mar 31, 2017 at 20:46
  • Just saw that ;) Mar 31, 2017 at 20:47
  • You'll also need to escape the backslash with double backslaches: String regExp = '<style>[^<]*<\\/style>|<\\/?\\w*\\b[^>]*>'; Pattern tagPattern = Pattern.compile(regExp); String plainTextBody = tagPattern.matcher(emailContent).replaceAll(''); Dec 2, 2021 at 12:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .