You are currently viewing Send Email Using Custom Email Template In Salesforce

Send Email Using Custom Email Template In Salesforce

Sharing is caring!

A pre-formatted email that you may use as a template lets you generate and send emails quickly. It also makes sure that the right message gets sent. Salesforce email templates can help you work more efficiently and send messages consistently. You may rapidly send emails containing field data from Salesforce records like Contacts, Leads, Opportunities, or custom objects using email templates with merge fields. You can use email templates when sending a List Email to a large group of people or just one person. You can make your own template or use one made by the administrator or your manager. 

There are two email templates in Salesforce: Classic Email Templates and Lightning Email Templates. It is not possible to automate Lightning Email templates, unlike the Classic Email Templates. 

In this blog, we will provide a step-by-step process to create a custom email template and send an email using a custom email template in Salesforce. Furthermore, we will also show you how you can dynamically replace the value merge field in the Email template in the Apex in runtime. 

Steps For Sending Email Using Custom Email Template In Salesforce 

Part 1: Create a custom(without using Letterhead) email template. 

Part 2: Send an email using a custom email template. 

Lets’ deep dive into how to create a custom(without using Letterhead) email template:

Step 1: First, log into your Salesforce Org with your credentials. 

Step 2: Go to Setup ->Classic Email Templates and click on New Template Button, as shown in the figure below.

Step 3: Choose the Custom(without using Letterhead) radio button and click on the Next button, as shown below. 

Step 4: Fill up all the details as shown in the diagram below and check the “Available for Use” checkbox; then, click on the Next button, as shown in the figure below. 

Step 5: Now, content is entered in the Email Body. Next, Click on the Next button. 

Replace the HTML Body with the following code: 

<body style=”background-color:grey”>

    <table align=”center” border=”0″ cellpadding=”0″ cellspacing=”0″

           width=”550″ bgcolor=”white” style=”border:2px solid black”>

        <tbody>

            <tr>

                <td align=”center”>

                    <table align=”center” border=”0″ cellpadding=”0″

                           cellspacing=”0″ class=”col-550″ width=”550″>

                        <tbody>

                            <tr>

                                <td align=”center” style=”background-color: Blue;

                                           height: 50px;”>

                                    <a href=”#” style=”text-decoration: none;”>

                                        <p style=”color:white;

                                                  font-weight:bold;”>

                                            {!ContactName}

                                        </p>

                                    </a>

                                </td>

                            </tr>

                        </tbody>

                    </table>

                </td>

            </tr>

            <tr style=”height: 300px;”>

                <td align=”center” style=”border: none;

                           border-bottom: 2px solid black; 

                           padding-right: 20px;padding-left:20px”>

                    <p style=”font-weight: bolder;font-size: 42px;

                              letter-spacing: 0.025em;

                              color:black;”>

                        Hello  {!ContactName}!

                        <br> Cloud Analogy is a global CRM solution.

                    </p>

                </td>

            </tr>

            <tr style=”display: inline-block;”>

                <td style=”height: 150px;

                           padding: 20px;

                           border: none; 

                           border-bottom: 2px solid #361B0E;

                           background-color: white;”>

                    <h2 style=”text-align: left;

                               align-items: center;”>

                        As the world’s leading CRM consulting partner, we strive for authenticity over perfection. 

                   </h2>

                    <p class=”data”

                       style=”text-align: justify-all;

                              align-items: center; 

                              font-size: 15px;

                              padding-bottom: 12px;”>

                        We are proficient in delivering a plethora of CRM consulting services to help our clients and their customers with the most compelling user experience.

                    </p>

                    <p>

                        <a href=

“https://www.cloudanalogy.com/”

                           style=”text-decoration: none; 

                                  color:black; 

                                  border: 2px solid black; 

                                  padding: 10px 30px;

                                  font-weight: bold;”> 

                           Read More 

                      </a>

                    </p>

                </td>

            </tr>

            <tr style=”border: none; 

            background-color: blue; 

            height: 40px; 

            color:white; 

            padding-bottom: 20px; 

            text-align: center;”>

<td height=”40px” align=”center”>

    <p style=”color:white; 

    line-height: 1.5em;”>

     {!ContactName}

    </p>

</td>

</tr>

<tr>

<td style=”font-family:’Open Sans’, Arial, sans-serif;

           font-size:11px; line-height:18px; 

           color:#999999;” 

    valign=”top”

    align=”center”>

<a href=”#”

   target=”_blank” 

   style=”color:#999999; 

          text-decoration:underline;”>PRIVACY STATEMENT</a> 

          | <a href=”#” target=”_blank” 

          style=”color:#999999; text-decoration:underline;”>TERMS OF SERVICE</a> 

          | <a href=”#”

          target=”_blank” 

          style=”color:#999999; text-decoration:underline;”>RETURNS</a><br>

                  © 2022 cloudAnalogy. All Rights Reserved.<br>

                  If you do not wish to receive any further 

                  emails from us, please

                  <a href=”#”

                  target=”_blank”

                  style=”text-decoration:none; 

                         color:#999999;”>unsubscribe</a>

            </td>

              </tr>

            </tbody></table></td>

        </tr>

        <tr>

          <td class=”em_hide”

          style=”line-height:1px;

                 min-width:700px;

                 background-color:#ffffff;”>

              <img alt=”” 

              src=”images/spacer.gif” 

              style=”max-height:1px; 

              min-height:1px; 

              display:block; 

              width:700px; 

              min-width:700px;” 

              width=”700″

              border=”0″ 

              height=”1″>

              </td>

        </tr>

        </tbody>

    </table>

</body>

Step 6: Next, Copy text from the HTML version button gets clicked to get a warning alert message. Click on the “OK” button to populate your HTML body in text format. Click on the Save button, as shown in the below figure. 

Moving on to the next part, let’s understand how to Send an Email Using a Custom Email Template.

I will also show you how you can replace the value merge field value in the email template in the Apex in runtime.

Step 1: First of all, we create a Lightning Component. 

<aura:component controller=”EmailTemplateController_Apex” implements=”force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction” access=”global” >

    <aura:attribute name=”EmailSubject” type=”string” default=”Email Template”/>

    <aura:attribute name=”EmailAddress” type=”string”/>

    <aura:attribute name=”Emailbody” type=”string” default=””/>

    <aura:attribute name=”recordId” type=”string”/>

    <aura:handler name=”init” value=”{!this}” action=”{!c.doInit}” /> 

    <lightning:layout multipleRows=”true”>

        <lightning:layoutItem size=”12″ class=”slds-p-right_small”>

            <lightning:input label=”Email Address” name=”divsubject” value=”{!v.EmailAddress}” class=”slds-p-left_small”/>

        </lightning:layoutItem>

        <lightning:layoutItem size=”12″ class=”slds-p-right_small”>

            <lightning:input label=”Subject” name=”divsubject” value=”{!v.EmailSubject}” class=”slds-p-left_small”/>

        </lightning:layoutItem>

        <lightning:layoutItem size=”12″ class=”slds-p-top_small slds-p-bottom_small slds-p-left_small slds-p-right_small”>

            <lightning:inputRichText value=”{!v.Emailbody}” placeholder=””/>

        </lightning:layoutItem>

        <button class=”slds-button slds-button_brand slds-float_right” onclick=”{!c.onSendEmail}”>Send</button>

    </lightning:layout>

</aura:component>

Step 2: Next, we create a JavaScript Controller.  

({

doInit: function (c, e, h) {

        try {

            h.doInit_helper(c,e,h);

        } catch (err) {

            console.log(err);

        }

    },

    onSendEmail :  function(c,e,h) {

        try {

            h.onSendEmail_Helper(c,e,h);

        } catch (err) {

            console.log(err);

        }

},

})

Step 3: Then, we create a Lightning helper.  

({

    doInit_helper : function(c,e,h) {

        try{

            var Recordid = c.get(‘v.recordId’);

            var emailtemplete = ‘<p>Dear ContactName,</p><br/><p>Thank you for contacting us, We will contact you again on your Email.</p>’;

            c.set(‘v.Emailbody’,emailtemplete);

            var action = c.get(“c.getEmailAddress”);

            action.setParams({

                “Recordid”:Recordid

            });

            action.setCallback(this, function(response){

                if(response.getState()===”SUCCESS”){

                    var returnval = response.getReturnValue();

                    if (!$A.util.isEmpty(returnval)){

                        c.set(‘v.EmailAddress’,returnval);

                    }

                    else{

                        c.set(‘v.EmailAddress’,”);

                    }

                }

                else{

                    c.set(‘v.EmailAddress’,”);

                }

            });

            $A.enqueueAction(action);

        } catch (err) {

            console.log(err);

        }

    },

    onSendEmail_Helper  : function(c,e,h) {

        try{

            var EmailAddress = c.get(‘v.EmailAddress’);

            var EmailSubject =  c.get(‘v.EmailSubject’);

            var EmailBody =  c.get(‘v.Emailbody’);

            var Recordid = c.get(‘v.recordId’);

            var action = c.get(“c.SendMail_Apex”);

            action.setParams({

                “EmailAddress”:EmailAddress,

                “EmailSubject”:EmailSubject,

                “EmailBody”:EmailBody,

                “Recordid”:Recordid

            });

            action.setCallback(this, function(response){

                if(response.getState()===”SUCCESS”){

                    var returnval = response.getReturnValue();

                    if (!$A.util.isEmpty(returnval)){

                        c.set(‘v.EmailAddress’,returnval);

                    }

                    else{

                        c.set(‘v.EmailAddress’,”);

                    }

                }

                else{

                    c.set(‘v.EmailAddress’,”);

                }

            });

            $A.enqueueAction(action);

        } 

        catch (err) {

            console.log(err);

        }

    },

})

Step 4: We create an Apex class.  

public class EmailTemplateController_Apex {

    @AuraEnabled

    public static string getEmailAddress(string Recordid){

        try{

            if(Recordid !=null && String.isNotEmpty(Recordid)){

                Contact contactObj =  new Contact();

                contactObj = [select Id,Email from Contact where Id =: Recordid limit 1];

                return contactObj.Email;

            }

            return null;

        }catch(Exception ex){

            system.debug(‘Error at line’+ex.getLineNumber()+’Error is’+ex.getMessage());

        }

        return null;

    }

    @AuraEnabled

    public static void SendMail_Apex(string EmailAddress,string EmailSubject,string EmailBody,string Recordid){

        try{

            if(String.isNotEmpty(EmailAddress) && String.isNotEmpty(EmailSubject) && String.isNotEmpty(EmailBody)  && String.isNotEmpty(Recordid)){

                Contact contactObj =  new Contact();

                contactObj = [select Id,Email,Name from Contact where Id =: Recordid limit 1];

                String emailsbody = EmailBody;

                emailsbody = emailsbody.replace(‘ContactName’, string.valueof(contactObj.Name));

                emailsbody = emailsbody.replace(‘Address’, string.valueof(contactObj.Email));

                List<EmailTemplate> emailTemplates = new List<EmailTemplate>();

                emailTemplates = [SELECT ID, Name, HtmlValue, Subject,Body,DeveloperName, 

                                  TemplateStyle, TemplateType From EmailTemplate Where DeveloperName = ‘EmailHtmlTemplate’ LIMIT 10000];

                String plainText = emailTemplates[0].HtmlValue;

                String emailsAddress = EmailAddress;

                plainText = plainText.replace(‘{!ContactName}’, contactObj.Name);

                emailsbody  =  emailsbody+plainText;

                Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();

                message.toAddresses = new String[] { emailsAddress };

                    message.setSubject(EmailSubject);

                message.setHtmlBody(emailsbody);

                Messaging.SingleEmailMessage[] messages =new List<Messaging.SingleEmailMessage> {message};

                    Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);

            }

        }catch(Exception ex){

            system.debug(‘Error at line’+ex.getLineNumber()+’Error is’+ex.getMessage());

        }

    }

}

Below is the attached image of the component created :

Below is the attached image of the email received after the values were replaced:

Below is the full email template image:

Conclusion

A pre-formatted email is used as a template to let you generate and send emails quickly and ensure that the right message gets sent. The email templates in Salesforce help to improve productivity and ensure consistent messaging. It is possible to use email templates while mass emailing people with List Email or just to send to one person. One can create one’s own template or use the templates that Admin or your manager creates. 
Cloud Analogy, one of the top-notch Salesforce Consulting companies, will enable you to generate and send emails quickly using custom email templates. We assure you that our cost-effective Salesforce Consulting services will grow your business in countless ways. Reach out to our expert and certified team at Cloud Analogy and start your project today.

ajay

Ajay Dubedi

CEO | Founder
Ajay Dubedi, the founder and CEO of Cloud Analogy, is a prominent Salesforce Sales, Service, and Marketing cloud Consultant with a rich expertise in handling challenging business models. Ajay has assisted and implemented solutions in industries comprising Banking, Health Care, Networking, Education, Telecommunication and Manufacturing. Ajay is globally acclaimed for his extensive experience in APEX Programming, VisualForce pages, Triggers, Workflows, Page Layouts, Roles, Profiles, Reports & Dashboards.

Hire the best Salesforce Implementation Partner. Choose Cloud Analogy, the world's most preferred Salesforce Implementation Company that provides custom CRM Implementation services.

Leave a Reply

× How can I help you?