Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • The Ultimate Guide to Data Cleanup Techniques for Salesforce
    • How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI
    • Top Mistakes Developers Make in Salesforce Apex Triggers
    • Introducing Agentforce3 to Salesforce Developers
    • The Ultimate Guide to Apex Order of Execution for Developers
    • How to Handle Bulkification in Apex with Real-World Use Cases
    • How to Confidently Manage Transactions in Salesforce Apex
    • Building a Dynamic Tree Grid in Lightning Web Component
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Saturday, August 2
    • Home
    • Salesforce Platform
      • Architecture
      • Apex
      • Lightning Web Components
      • Integration
      • Flows & Automation
      • Best Practices
      • Questions
      • News
      • Books Testimonial
    • Industries
      • Artificial Intelligence
    • Hire Me
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Downloads
      • Salesforce Release Notes
      • Apex Coding Guidelines
    • About Us
      • Privacy Policy
    • Contact Us
    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 Sahni6 Mins Read

    How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI

    July 28, 2025
    By Dhanik Lal Sahni7 Mins Read

    Top Mistakes Developers Make in Salesforce Apex Triggers

    July 25, 2025
    By Dhanik Lal Sahni14 Mins Read

    The Ultimate Guide to Apex Order of Execution for Developers

    July 20, 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
    SFBenTopDeveloper
    Ranked #4 Salesforce Developer Blog by ApexHours.com
    ApexHoursTopDevelopers
    Categories
    Archives
    Tags
    apex (116) apex best practices (5) apex code best practice (10) apex code optimization (6) Apex logging (4) apex rest (11) apex trigger best practices (6) architecture (22) Asynchronous apex (9) AWS (5) batch apex (10) best code practice (4) code optimization (9) custom metadata types (5) design principle (9) flow (16) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (66) lightning-combobox (5) lightning-datatable (10) lightning component (32) Lightning web component (64) lwc (53) named credential (8) news (4) optimize apex (5) optimize apex code (6) optimize apex trigger (5) Permission set (4) Queueable (9) queueable apex (4) rest api (23) salesforce (150) salesforce apex (52) salesforce api integration (5) Salesforce Interview Question (5) 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

    MailChimp

    Expert Salesforce Developer and Architect
    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • The Ultimate Guide to Data Cleanup Techniques for Salesforce
    • How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI
    • Top Mistakes Developers Make in Salesforce Apex Triggers
    • Introducing Agentforce3 to Salesforce Developers
    • The Ultimate Guide to Apex Order of Execution for Developers
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • Top 10 Salesforce CRM Trends to Watch in 2025 July 18, 2025
    • Discover the Top 10 Salesforce AppExchange Apps to Boost Productivity July 10, 2025
    • 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
    Archives
    Categories
    Tags
    apex (116) apex best practices (5) apex code best practice (10) apex code optimization (6) Apex logging (4) apex rest (11) apex trigger best practices (6) architecture (22) Asynchronous apex (9) AWS (5) batch apex (10) best code practice (4) code optimization (9) custom metadata types (5) design principle (9) flow (16) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (66) lightning-combobox (5) lightning-datatable (10) lightning component (32) Lightning web component (64) lwc (53) named credential (8) news (4) optimize apex (5) optimize apex code (6) optimize apex trigger (5) Permission set (4) Queueable (9) queueable apex (4) rest api (23) salesforce (150) salesforce apex (52) salesforce api integration (5) Salesforce Interview Question (5) 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.