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?
2 Answers
I think rather than using any RegEx, you can just use a built in String method: stripHtmlTags.
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. Commented 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/… Commented 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 ♦Commented Mar 31, 2017 at 20:46
-
-
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(''); Commented Dec 2, 2021 at 12:38
<\/?\w*\b[^>]*>
.or
in a search for<style>
tags and include their contents. For example:<style>[^<]*<\/style>|<\/?\w*\b[^>]*>
.