Recently, I worked on a requirement where in I had to send an email by using APEX and I had to prepare the HTML body within APEX itself. As part of it, there has to be a clickable link in the email which should take the user to the Salesforce record after clicking on it and we should not hardcode the URL in the code.

So, here is the code below to get the logged in user’s URL and concatenate it with the Salesforce record ID:

String u=System.Url.getSalesforceBaseURL().toExternalForm();//this returns the base URL of the Salesforce instance as String.
String ufinal=u+’/’+POId;//POId is the variable that holds Id of the custom object record.

or you can write the above code in one line:

String ufinal = URL.getSalesforceBaseUrl().toExternalForm() + ‘/’ + POId;