0

After querying an EmailMessage

select id, subject, textbody from EmailMessage

I get the following textbody value displayed when rendered to a Visualforce Page:

Email reply --------------- Original Message --------------- From: Doe, John [john.doe@email.com] Sent: 2/22/2019 11:50 AM To: jane.doe@email.com Subject: RE: Sandbox: RE: This is a test email Email reply -----Original Message----- From: john.doe@email.com [mailto:jane.doe@email.com] Sent: Friday, February 22, 2019 11:48 AM To: Doe, Jane Subject: Sandbox:

However, if I debug the textbody it is line/break separated:

  • Email reply
  • --------------- Original Message ---------------
  • From: Doe, John [john.doe@email.com]
  • Sent: 2/22/2019 11:50 AM To: jane.doe@email.com
  • Subject: RE: Sandbox: RE: This is a test email
  • Email reply
  • -----Original Message-----
  • From: john.doe@email.com [mailto:jane.doe@email.com]
  • Sent: Friday, February 22, 2019 11:48 AM
  • To: Doe, Jane Subject: Sandbox:

How do I parse the textbody value from EmailMessage so that that is it is readable line by line as expected by the debug log. I'm assuming there is some sort of line break indicator?

3

It's not the line breaks that are the problem, it's how HTML treats line breaks by default (white-space: normal), which collapses multiple white space characters (space, tab, new line, and carriage return) into single white spaces. There are two general methods for fixing this.


CSS

The easiest way to fix the problem would be to use CSS:

<div style="white-space: pre-line;">{!emailBody}</div>

The white-space style will convert the line breaks in the body to actual line breaks in the rendered result.


Encode Line Breaks as Line Breaks (<br/>)

You can use the string replace method:

String output = emailBody.replace('\r\n','\n').replace('\n','\r').replace('\r','<br/>');

Because we can have sequences of \r\n, \n, or \r, we need standardize the output. We do this by first replacing CRLF (\r\n) to a normal \n, then convert all of the \n to \r, and finally replace \r with the HTML equivalent, <br/>. This should work correctly for any form of encoded line breaks.

2
  • Awesome. I opted for the line break encoding option as adding a class to the outputlabel component I was using to render this did not seem to convert the line breaks, but that could've easily be a styling conflict on my side. Besides the debug log, how did you know the textbody retained the line breaks "\r\n" as the query results does not seem to display these. – S.B. Mar 10 '19 at 22:59
  • @S.B. it's in the documentation. Any field that has a type of "textarea" will preserve line breaks in the database. It's always worth checking out the docs or the describe calls to see the attributes of a field. – sfdcfox Mar 10 '19 at 23:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.