function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SFDC@ErrorSFDC@Error 

Send Email using lightning component

Hi All

How can i send email using lightning component with insert template selection option? I have tried below, but unable to add insert template option. can anyone help me this 
public class EmailSendController {
 @AuraEnabled 
    public static void sendMailMethod(String mMail ,String mSubject ,String mbody){
    
     List<Messaging.SingleEmailMessage> mails =  new List<Messaging.SingleEmailMessage>();     
  
     // Step 1: Create a new Email
       Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    
    // Step 2: Set list of people who should get the email
       List<String> sendTo = new List<String>();
       sendTo.add(mMail);
       mail.setToAddresses(sendTo);
    
    // Step 3: Set who the email is sent from
       mail.setReplyTo('noreply@gmail.com'); // change it with your mail address.
       mail.setSenderDisplayName('salesforce User'); 
    
    // Step 4. Set email contents - you can use variables!
      mail.setSubject(mSubject);
      mail.setHtmlBody(mbody);
    
    // Step 5. Add your email to the master list
      mails.add(mail);
    
  // Step 6: Send all emails in the master list
     Messaging.sendEmail(mails);
   }   
}
 
<aura:component controller="EmailSendController">
   <!--Part 1 [for attribute declare]-->  
   <aura:attribute name="email" type="string"/>
   <aura:attribute name="subject" type="string"/>
   <aura:attribute name="body" type="string"/>
   <aura:attribute name="mailStatus" type="boolean" default="false"/>
   
   <!---Part 2 [header part] -->  
   <div class="slds-page-header" role="banner">
      <h1 class="slds-page-header__title slds-m-right--small slds-align-middle slds-truncate" title="this should match">
         Quick Email Send.
      </h1>
      <div class="slds-text-color--weak">by sfdcMonkey.com</div>
   </div>
 
   <!---Part 3 [message display part] --> 
   <aura:if isTrue="{!v.mailStatus}">
      <div role="alertdialog" tabindex="-1" aria-labelledby="prompt-heading-id" aria-describedby="prompt-message-wrapper" class="slds-modal slds-fade-in-open slds-modal--prompt">
         <div class="slds-modal__container">
            <div class="slds-modal__header slds-theme--error slds-theme--alert-texture">
               <h2 class="slds-text-heading--medium" id="prompt-heading-id">Mail Status</h2>
            </div>
            <div class="slds-modal__content slds-p-around--medium">
               <div>
                  <p>Email Sent successfully to {!v.email}</p>
               </div>
            </div>
            <div class="slds-modal__footer slds-theme--default">
               <button class="slds-button slds-button--brand" onclick="{!c.closeMessage}">Close</button>
            </div>
         </div>
      </div>
      <div class="slds-backdrop slds-backdrop--open"></div>
   </aura:if>
   
   <!---Part 4 [mail fourm part]-->   
   <div class="slds-m-around--medium">
      <div class="slds-container--medium">
         <div class="slds-form--stacked">
            <div class="slds-form-element">
               <label class="slds-form-element__label" for="CC">Email</label>
               <div class="slds-form-element__control">
                  <ui:inputEmail class="slds-input" aura:id="email"  value="{!v.email}" required="true" placeholder="abc@email.com"/>
               </div>
            </div>
            <div class="slds-form-element">
               <label class="slds-form-element__label" for="CC">Subject</label>
               <div class="slds-form-element__control">
                  <ui:inputText class="slds-input" aura:id="subject"  value="{!v.subject}" placeholder="Subject"/>
               </div>
            </div>
            <div class="slds-form-element">
               <label class="slds-form-element__label" for="textareaSample2">Mail Body</label>
               <div class="slds-form-element__control">
                  <lightning:inputRichText aura:id="body" value="{!v.body}" />
               </div>
            </div>
            <div class="slds-form-element">    
               <button class="slds-button slds-button--brand" onclick="{!c.sendMail}">Send</button>
            </div>
         </div>
      </div>
   </div>
</aura:component>
 
({
    sendMail: function(component, event, helper) {
        // when user click on Send button 
        // First we get all 3 fields values 	
        var getEmail = component.get("v.email");
        var getSubject = component.get("v.subject");
        var getbody = component.get("v.body");
        // check if Email field is Empty or not contains @ so display a alert message 
        // otherwise call call and pass the fields value to helper method    
        if ($A.util.isEmpty(getEmail) || !getEmail.includes("@")) {
            alert('Please Enter valid Email Address');
        } else {
            helper.sendHelper(component, getEmail, getSubject, getbody);
        }
    },
 
    // when user click on the close buttton on message popup ,
    // hide the Message box by set the mailStatus attribute to false
    // and clear all values of input fields.   
    closeMessage: function(component, event, helper) {
        component.set("v.mailStatus", false);
        component.set("v.email", null);
        component.set("v.subject", null);
        component.set("v.body", null);
    },
})
 
({
    sendHelper: function(component, getEmail, getSubject, getbody) {
        // call the server side controller method 	
        var action = component.get("c.sendMailMethod");
        // set the 3 params to sendMailMethod method   
        action.setParams({
            'mMail': getEmail,
            'mSubject': getSubject,
            'mbody': getbody
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var storeResponse = response.getReturnValue();
                // if state of server response is comes "SUCCESS",
                // display the success message box by set mailStatus attribute to true
                component.set("v.mailStatus", true);
            }
 
        });
        $A.enqueueAction(action);
    },
})

 
Khan AnasKhan Anas (Salesforce Developers) 
Hi,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Application:
<aura:application extends="force:slds">
    <c:SendEmailSelectTemplate/>
</aura:application>

Component:
<aura:component controller="SendEmailSelectTemplateC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <aura:attribute name="PageHeading" type="String" default="Send Email"/>
    <aura:attribute name="mydata" type="Object"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:attribute name="selIds" type="List"/>
    <aura:attribute name="selectedRows" type="List" />
    <aura:attribute name="selTempl" type="String" description=""/>
    <aura:attribute name="templates" type="EmailTemplate[]" default="[]"/>
    <aura:attribute name="templDetail" type="EmailTemplate" default="{}" />
    
    <aura:handler name="init" value="{!this}" action="{!c.doinit}"/>
    
    <div class="slds-m-top--xx-large" >
        <div class="slds-page-header">
            <div class="slds-align--absolute-center">
                <div class="slds-text-heading--large">
                    {!v.PageHeading}
                </div>
            </div>
        </div>
    </div>
    <br/>
    
    <lightning:datatable aura:id="tableid"
                         data="{! v.mydata }" 
                         columns="{! v.mycolumns }" 
                         keyField="Id" 
                         selectedRows="{! v.selectedRows }"
                         onrowselection="{! c.handleRowAction }" />
    <br/>
    
    <lightning:select name="SelectDivision" label="Select a Template:" aura:id="templateId" value="{!v.selTempl}" onchange="{!c.onSelectTemplate}">
        <option text="None" value=""/>        
        <aura:iteration items="{!v.templates}" var="item">
            <option text="{!item.Name}" value="{!item.Id}"/>
        </aura:iteration> 
    </lightning:select>
    <br/>
    
    <lightning:button label="Send Email" onclick="{!c.sendMail}" 
                      variant="brand" iconName='utility:email'/>
</aura:component>

Controller:
({
    doinit : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Name', fieldName: 'Name', type: 'text'},
            {label: 'Email', fieldName: 'Email', type: 'text'}
        ]);       
        
        helper.getContacts(component, event);
        helper.getEmailTempaltes(component, event);
    },
    
    onSelectTemplate : function(component, event, helper){
        var templId = component.get("v.selTempl");
        console.log('templId -> ' + templId);
        var action = component.get("c.getTemplateDetails");
        action.setParams({templteId:templId});
        action.setCallback(this,function(response){
            var loadResponse = response.getReturnValue();
            console.log('templates..!',loadResponse);
            
            if(!$A.util.isEmpty(loadResponse)){
                component.set("v.templDetail",loadResponse);
            }
        });
        $A.enqueueAction(action);
    },
    
    handleRowAction : function(component, event, helper){
        var selRows = event.getParam('selectedRows');
        var rowsIds = [];
        for (var i = 0; i < selRows.length; i++){
            rowsIds.push(selRows[i].Id);
        }
        component.set("v.selIds",rowsIds);
    },
    
    sendMail : function(component, event, helper){
        var selectedrowsid = component.get('v.selIds');
        console.log('selectedrowsid-->>> ' + JSON.stringify(selectedrowsid));
        var templateId = component.get('v.templDetail');
        var action = component.get("c.send");
        action.setParams({ 'eid': selectedrowsid, 'tid': templateId});
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                if(selectedrowsid != ''){
                    alert('Email Sent Successfully');
                }
                else{
                    alert('Select Recipients');
                }
                component.set('v.selectedRows', '');
                component.set('v.selTempl','');
            }
        });
        $A.enqueueAction(action);
    },
})

Helper:
({
    getContacts : function(component, event) {
        var action1 = component.get('c.cont');
        action1.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                component.set('v.mydata',response.getReturnValue());
            }
            else if (state === "ERROR"){
                var errors = response.getError();
                if(errors){
                    if(errors[0] && error[0].message){
                        console.log('Error Message: ' + errors[0].message);
                    }
                }
                else{
                    console.log('Unknown Error');
                }
            }
        });
        $A.enqueueAction(action1);
    },
    
    getEmailTempaltes : function(component, event) {
        var action = component.get("c.getTemplates");
        action.setCallback(this,function(response){
            var loadResponse = response.getReturnValue();
            console.log('templates..!',loadResponse);
            
            if(!$A.util.isEmpty(loadResponse)){
                component.set('v.templates',loadResponse);
            }
        });
        $A.enqueueAction(action);
    },
})

Apex:
public class SendEmailSelectTemplateC {
    
    @AuraEnabled
    public static list<EmailTemplate> getTemplates(){
        //RelatedEntityType='Account' AND 
        list<EmailTemplate> emailTemp = new list<EmailTemplate>();
        emailTemp = [SELECT Id,Name,Subject,TemplateType FROM EmailTemplate WHERE TemplateType IN ('custom','text')];
        return emailTemp;
    }
    
    @AuraEnabled
    public static List<Contact> cont(){
        List<Contact> c = [SELECT Id, Name, Email FROM Contact LIMIT 5];
        return c;
    }
    
    @AuraEnabled 
    public static Id getTemplateDetails(string templteId){        
        EmailTemplate emailTemp = new EmailTemplate();
        //list<EmailTemplate> emailTempLst = new list<EmailTemplate>();
        emailTemp = [SELECT Id FROM EmailTemplate WHERE ID=: templteId];
        return emailTemp.Id;
    }
    
    @AuraEnabled
    public static void send(List<String> eid, String tid){
        List<Messaging.SingleEmailMessage> mails =  new List<Messaging.SingleEmailMessage>();
        
        for(Contact cc : [SELECT Id, Name, Email FROM Contact WHERE Id IN : eid]){
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            
            String sendTo;
            sendTo = cc.Id;
            mail.setTargetObjectId(sendTo);
            
            mail.setTemplateId(tid);
            mail.setSenderDisplayName('Khan Anas');
            mail.setSaveAsActivity(false);
            
            mails.add(mail);
            Messaging.sendEmail(mails);
        }
    }
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
SFDC@ErrorSFDC@Error
Hay Anas
I have tried your code on standard case object with a custom email__c field, but it is not working means not going any mail.
public class SendEmailSelectTemplate {
    
    @AuraEnabled
    public static list<EmailTemplate> getTemplates(){
        //RelatedEntityType='Account' AND 
        list<EmailTemplate> emailTemp = new list<EmailTemplate>();
        emailTemp = [SELECT Id,Name,Subject,TemplateType FROM EmailTemplate WHERE TemplateType IN ('custom','text')];
        return emailTemp;
    }
    
    @AuraEnabled
    public static List<case> cont(){
        List<Case> c = [SELECT Id, CaseNumber,Email__c FROM Case];
        return c;
    }
    
    @AuraEnabled 
    public static Id getTemplateDetails(string templteId){        
        EmailTemplate emailTemp = new EmailTemplate();
        //list<EmailTemplate> emailTempLst = new list<EmailTemplate>();
        emailTemp = [SELECT Id FROM EmailTemplate WHERE ID=: templteId];
        return emailTemp.Id;
    }
    
    @AuraEnabled
    public static void send(List<String> eid, String tid){
        List<Messaging.SingleEmailMessage> mails =  new List<Messaging.SingleEmailMessage>();
        
        for(Case cc : [SELECT Id,CaseNumber, Email__c FROM Case WHERE Id IN : eid]){
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            
            String sendTo;
            sendTo = cc.id;
            mail.setTargetObjectId(sendTo);
            
            mail.setTemplateId(tid);
            mail.setSenderDisplayName('Khan Anas');
            mail.setSaveAsActivity(false);
            
            mails.add(mail);
            Messaging.sendEmail(mails);
        }
    }
}
 
<aura:component controller="SendEmailSelectTemplate"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <aura:attribute name="PageHeading" type="String" default="Send Email"/>
    <aura:attribute name="mydata" type="Object"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:attribute name="selIds" type="List"/>
    <aura:attribute name="selectedRows" type="List" />
    <aura:attribute name="selTempl" type="String" description=""/>
    <aura:attribute name="templates" type="EmailTemplate[]" default="[]"/>
    <aura:attribute name="templDetail" type="EmailTemplate" default="{}" />
    
    <aura:handler name="init" value="{!this}" action="{!c.doinit}"/>
    
    <div class="slds-m-top--xx-large" >
        <div class="slds-page-header">
            <div class="slds-align--absolute-center">
                <div class="slds-text-heading--large">
                    {!v.PageHeading}
                </div>
            </div>
        </div>
    </div>
    <br/>
    <lightning:select name="SelectDivision" label="Select a Template:" aura:id="templateId" value="{!v.selTempl}" onchange="{!c.onSelectTemplate}">
        <option text="None" value=""/>        
        <aura:iteration items="{!v.templates}" var="item">
            <option text="{!item.Name}" value="{!item.Id}"/>
        </aura:iteration> 
    </lightning:select>
    <br/>
    
    <lightning:datatable aura:id="tableid"
                         data="{! v.mydata }" 
                         columns="{! v.mycolumns }" 
                         keyField="Id" 
                         selectedRows="{! v.selectedRows }"
                         onrowselection="{! c.handleRowAction }" />
    <br/>
    
    
    
    <lightning:button label="Send Email" onclick="{!c.sendMail}" 
                      variant="brand" iconName='utility:email'/>
</aura:component>
 
({
    doinit : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'CaseNumber', fieldName: 'CaseNumber', type: 'text'},
            {label: 'Email', fieldName: 'Email__c', type: 'text'}
        ]);       
        
        helper.getContacts(component, event);
        helper.getEmailTempaltes(component, event);
    },
    
    onSelectTemplate : function(component, event, helper){
        var templId = component.get("v.selTempl");
        console.log('templId -> ' + templId);
        var action = component.get("c.getTemplateDetails");
        action.setParams({templteId:templId});
        action.setCallback(this,function(response){
            var loadResponse = response.getReturnValue();
            console.log('templates..!',loadResponse);
            
            if(!$A.util.isEmpty(loadResponse)){
                component.set("v.templDetail",loadResponse);
            }
        });
        $A.enqueueAction(action);
    },
    
    handleRowAction : function(component, event, helper){
        var selRows = event.getParam('selectedRows');
        var rowsIds = [];
        for (var i = 0; i < selRows.length; i++){
            rowsIds.push(selRows[i].Id);
        }
        component.set("v.selIds",rowsIds);
    },
    
    sendMail : function(component, event, helper){
        var selectedrowsid = component.get('v.selIds');
        console.log('selectedrowsid-->>> ' + JSON.stringify(selectedrowsid));
        var templateId = component.get('v.templDetail');
        var action = component.get("c.send");
        action.setParams({ 'eid': selectedrowsid, 'tid': templateId});
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                if(selectedrowsid != ''){
                    alert('Email Sent Successfully');
                }
                else{
                    alert('Select Recipients');
                }
                component.set('v.selectedRows', '');
                component.set('v.selTempl','');
            }
        });
        $A.enqueueAction(action);
    },
})
 
({
    getContacts : function(component, event) {
        var action1 = component.get('c.cont');
        action1.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                component.set('v.mydata',response.getReturnValue());
            }
            else if (state === "ERROR"){
                var errors = response.getError();
                if(errors){
                    if(errors[0] && error[0].message){
                        console.log('Error Message: ' + errors[0].message);
                    }
                }
                else{
                    console.log('Unknown Error');
                }
            }
        });
        $A.enqueueAction(action1);
    },
    
    getEmailTempaltes : function(component, event) {
        var action = component.get("c.getTemplates");
        action.setCallback(this,function(response){
            var loadResponse = response.getReturnValue();
            console.log('templates..!',loadResponse);
            
            if(!$A.util.isEmpty(loadResponse)){
                component.set('v.templates',loadResponse);
            }
        });
        $A.enqueueAction(action);
    },
})