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
Aidel BruckAidel Bruck 

How to get a line break on sethtmlbody

I have an email alert being sent by a trigger with the sethtmlbody()
I am trying to get a linebreak in the body but It is not working
This is how I set the body
mail.setSubject('New Document Added');
          String body = 'Please note: A new document has been added to '+a[0].Name+' \n  ';
        body += 'File name: '+ newdoc.title+'.\n\r' ;
        body += 'Created By: '+ username+ '.\n\r';
        body += 'Created Date: '+ newdoc.CreatedDate+ '.\n\r';
        body += 'link to file: '+ System.URL.getSalesforceBaseUrl().getHost()+'/'+newdoc.Id;
          mail.setHtmlBody(body);

I tried \r
I tried </BR>
And I still cant get a line break in the email, its all one long line
How can I get a line break?
Best Answer chosen by Aidel Bruck
Khan AnasKhan Anas (Salesforce Developers) 
Hi Aidel,

Greetings to you!

To insert a line break in an email message using Apex in Salesforce, we have to use <br/> or <br> tag. 

Use below code, I have tried in my org and it is working fine.

mail.setSubject('New Document Added');
String body = 'Please note: A new document has been added to '+a[0].Name+' \n ';
body += 'File name: '+ newdoc.title+ '<br/>' ;
body += 'Created By: '+ username+ '<br/>';
body += 'Created Date: '+ newdoc.CreatedDate+ '<br/>';
body += 'link to file: '+ System.URL.getSalesforceBaseUrl().getHost()+'/'+newdoc.Id;
mail.setHtmlBody(body);

Or you can use below code also.

mail.setSubject('New Document Added');
String body = 'Please note: A new document has been added to '+a[0].Name+ ' \n ';
body += 'File name: '+ newdoc.title+ '<br><br>' ;
body += 'Created By: '+ username+ '<br><br>';
body += 'Created Date: '+ newdoc.CreatedDate+ '<br><br>';
body += 'link to file: '+ System.URL.getSalesforceBaseUrl().getHost()+'/'+newdoc.Id;
mail.setHtmlBody(body);


I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas