Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • 10 Salesforce Chrome Extensions to Boost Your Productivity
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    • Top 10 PMD Issues Salesforce Developers Should Focus on in Apex
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Saturday, June 21
    • Home
    • Architecture
    • Salesforce
      • News
      • Apex
      • Integration
      • Books Testimonial
    • Questions
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Integration Posts
    • Downloads
    • About Us
      • Privacy Policy
    SalesforceCodex
    Home»Salesforce»Send Email Using Email Template and Apex

    Send Email Using Email Template and Apex

    Dhanik Lal SahniBy Dhanik Lal SahniMay 10, 20197 Comments2 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Send Email Using Email Template and Apex
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Send Email Using Email Template and Apex

    Sending Email is one of some important task in salesforce application like sending any report, send task information etc. We have below options to send email in salesforce.

    • Use Email Template and SingleEmailMessage class
    • Create VF Page and Send it using Apex

    Let us see first approach in this post. For sending email with attachment below steps are required

    1. Create Email Template
    2. Send Email using Apex
    3. Create Lightning Action component
    4. Create Lightning Action on Object
    5. Add button on Page layout

    We can send any report as attachment also. Let us see step by step information to send email using Email Template.

    1. Create Email Template

    Email templates can be used to increase productivity and ensure consistent messaging. Email templates with merge fields let us quickly send emails that include field data from Salesforce records. We have used account record to create template.

    Open email template page by navigating Setup->Classic Email Template->New Template->Visual Force

    Provide email template information

    Edit Template to create decline letter. This letter will be sent as email so Different HTML body and Email attachment will be provided.

    Create email body based on your requirement.  After saving email body it will show HTML preview.

     

    2. Send Email using Apex

    Let us create an Apex method which will send email based on current record and above template id. Messaging.SingleEmailMessage is used to send single email message to respective user.

    @AuraEnabled
    public class CreditCardController {
            public void sendEmail(string acctid)
            {
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
                mail.setTargetObjectId(UserInfo.getUserId()); 
                //Change with Template ID
                mail.setTemplateId('00X7F000000EiTl'); 
                
                //Record ID for which letter will be generated
                mail.setWhatId(acctid); 
                mail.setBccSender(false); 
                mail.setUseSignature(false); 
                mail.setSenderDisplayName('Card Division'); 
                mail.setSaveAsActivity(false); 
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            }
    }
    

    3. Create Lightning Action component

    Button can be added to classic page layout and Lightning layout to send email. Let us create a lightning component which will work as quick action button. We will add this on our layout.

    <aura:component controller="CreditCardController"
                    implements="flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickActionWithoutHeader" >
        <aura:attribute name="recordId" type="Id" />
        <aura:handler name="init" value="{!this}" action="{!c.apexExecute}"/>
    </aura:component>
    ({
            apexExecute : function(component, event, helper) {
                //Call Your Apex Controller Method.
                var action = component.get("c.sendEmail");
                action.setParams({
                    'acctid': ''+component.get('v.recordId')+''
                });
    
                action.setCallback(this, function(response) {
                    var state = response.getState();
                        if (state === "SUCCESS") {
                            //after code
                            response.getReturnValue();
    
                            $A.get("e.force:closeQuickAction").fire();
                        } 
                });
                
                $A.enqueueAction(action);
    	}
    })

    4. Create Lightning Action on Object

    Create one Lightning action button on account page.  Select lightning component which we have created above.5. Add button on Page layout

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleEnforce Field-Level Security Permissions for SOQL Queries – Spring 19 Release
    Next Article Call Lightning Component using Formula Link
    Dhanik Lal Sahni
    • Website

    Related Posts

    By Dhanik Lal Sahni9 Mins Read

    10 Salesforce Chrome Extensions to Boost Your Productivity

    June 1, 2025
    By Dhanik Lal Sahni4 Mins Read

    How to Build a Generic Modal Window in Lightning Web Component

    May 26, 2025
    By Dhanik Lal Sahni6 Mins Read

    Top 10 Salesforce Flow Features of Salesforce Summer ’25

    May 11, 2025
    View 7 Comments

    7 Comments

    1. Muni Prasad on May 4, 2020 3:27 pm

      Thats a nice tip. But i wanted to know, will this also work for custom objects?

      Reply
      • Dhanik Lal Sahni on May 4, 2020 9:42 pm

        Yes Muni. It will work for custom object also.

        Thank You,
        Dhanik

        Reply
    2. Pingback: Apex Send Email » LoginCast.Com

    3. Gaurav on August 11, 2021 4:06 pm

      Sir its not working for my custom object please help for me.

      Reply
      • Dhanik Lal Sahni on August 12, 2021 9:56 pm

        Hello Gaurav,

        What is not working. Please put complete detail, what error you are getting.

        Thank You,
        Dhanik

        Reply
    4. Pingback: Schedule Email alerts based on Business Hours in Salesforce

    5. Pingback: Apex Send Email • 3Z Acdemy

    Leave A Reply Cancel Reply

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • 10 Salesforce Chrome Extensions to Boost Your Productivity
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • Top 20 Salesforce Data Cloud Interview Questions & Answers for Admins June 5, 2025
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    Archives
    Categories
    Tags
    apex (111) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code analysis (3) code optimization (8) custom metadata types (5) design principle (9) flow (15) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (65) lightning-combobox (5) lightning-datatable (10) lightning component (31) Lightning web component (63) lwc (52) named credential (8) news (4) optimize apex code (4) optimize apex trigger (3) Permission set (4) pmd (3) Queueable (9) rest api (23) S3 Server (4) salesforce (142) salesforce apex (47) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Facebook X (Twitter) Instagram Pinterest YouTube Tumblr LinkedIn Reddit Telegram
    © 2025 SalesforceCodex.com. Designed by Vagmine Cloud Solution.

    Type above and press Enter to search. Press Esc to cancel.

    Ad Blocker Enabled!
    Ad Blocker Enabled!
    Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.