Hello Everyone, In this tutorial, I am going to provide a step-by-step process to send an email using a custom email template in Salesforce. In this unit, I will also show you how you can replace the value of merge field value in email template in the apex in runtime. So without wasting the time let's get started,

Send email using email template in Salesforce

Step 1:  Login to your Salesforce Org. and create a custom email template (Custom(without using Letterhead) Email Template in Salesforce) and keep template id for further reference.

Step 2: Open Developer Console.

Step 3: Go to File>New>Apex Class and create an Apex controller called SendEmailWithEmailTemplateReplace the following code. 

SendEmailWithEmailTemplate.apxc
 public class SendEmailWithEmailTemplate{
  
    public  SendEmailWithEmailTemplate() {            
    }    
    
    @RemoteAction
    public static string SendEmail(String toEmailAddress){
        String isSuccess='';
        try{
            //Query logged in User information
            User usr =[Select firstname, lastname from User WHERE Id =:Userinfo.getUserId()];  
            //Query email template
            EmailTemplate template=[SELECT Id,Body,HtmlValue,Subject FROM EmailTemplate WHERE Id = '00X0K000001dqzN'];
            //get template body
            String plainText = template.HtmlValue;
            //Replace merged field with user information
            plainText = plainText.replace('{!User.FirstName}', Usr.FirstName);
            plainText = plainText.replace('{!User.LastName}', Usr.LastName);
            
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setToAddresses(new List<String>{toEmailAddress});   
            mail.setHtmlBody(plainText);
            mail.setSubject(template.Subject); 
            Messaging.SendEmailResult [] results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});       
            isSuccess='SUCCESS';
        }
        catch(Exception ex){
            isSuccess=ex.getMessage()+'\n'+ex.getLineNumber()+'\n'+ex.getCause()+'\n'+ex.getStackTraceString();
        }
        return isSuccess;
    }
 }
Note: Please replace template Id with your template Id in the above code block.

Step 4: Go to File>New>Visualforce Page and create a new Visualforce Page called SendEmailUsingEmailTemplate and replace the following markup.

SendEmailUsingEmailTemplate .vfp
 <apex:page controller="SendEmailWithEmailTemplate">
    <apex:form id="frm">        
        <apex:pageBlock title="" id="pb">            
            <apex:pageblockButtons location="top">  
                <input type="text" id="txtEmailAddress"/>
                <apex:commandButton value="Send Email" onclick="sendEmail()" reRender="pb" />                
            </apex:pageblockButtons>            
        </apex:pageBlock>
        <script>
        function sendEmail(){  
            var toEmailAddress=document.getElementById('txtEmailAddress').value;
            if(toEmailAddress!=null && toEmailAddress!='' && toEmailAddress!=undefined){                
                if(validateEmail(toEmailAddress)){
                    SendEmailWithEmailTemplate.SendEmail(toEmailAddress,function(result,event){
                        if(event.status){
                            if(result=='SUCCESS'){
                                alert('Email Sent Sucessfully');
                            }
                            else{
                                alert(result);
                            }
                        }                
                    });
                }
                else{
                    alert('Please enter valid email address');
                }
            }
            else{
                alert('Please enter email address');
            }
        }
        
        function validateEmail(toEmailAddress){          
            var reg = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
            return reg.test(toEmailAddress);            
        }
        </script>
    </apex:form>
 </apex:page>

Output:
See also:

Conclusion:
Hope you like this tutorial, for any query or suggestions please feel free to comment.
Thank you.