function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Nandhini S 3Nandhini S 3 

\n not working in apex

Hi All,

We have an apex class to send out email. There is a string which has the body of the email. 
Example:
String str = 'Hi,' + '\n\n'+
'First line of the subject: '+variable1 +'\n'+
'Second line of the subject: '+variable2 +'\n';
This works fine when the value of variable1 is short (first and second line of the string comes in separate lines). If the value of variable1 is a long text then first and second line of the string comes in the same line.


 
SubratSubrat (Salesforce Developers) 
Hello Nandhini ,

In Apex, the "\n" character is not recognized as a line break in a string. Instead, you can use the "<br/>" HTML tag to create a line break in the email body. 

For example:
String str = 'Hi,<br/><br/>'+
'First line of the subject: '+variable1 +'<br/>'+
'Second line of the subject: '+variable2 +'<br/>';
By using the "<br/>" tag, each line will be displayed on a separate line in the email body, regardless of the length of the variable values.

If this helps , please mark this as Best Answer.
Thank you.
Nandhini S 3Nandhini S 3
Hi Subrat,

I tried using "<br/>" but the tag is just displayed in the email and there is no break in the lines.
Nandhini S 3Nandhini S 3
We are using emailMessage.setPlainTextBody() not htmlBody.
SubratSubrat (Salesforce Developers) 
Hello ,

Can you try with this :
String str = 'Hi,' + '\n\n'+
'First line of the subject: '+variable1 +'\n\n'+
'Second line of the subject: '+variable2 +'\n';

Hope this helps !
Thank you.
Nandhini S 3Nandhini S 3
The issue was actually in outlook settings. Thanks for your help Subrat.