+ Start a Discussion
Thulasi ReddysThulasi Reddys 

How we can send an email to selected contacts using lightning component?

Best Answer chosen by Thulasi Reddys
sfdcMonkey.comsfdcMonkey.com
HI Thulasi, here is the sample code :

apex class "
public with sharing class EmailWithCheckboxController {
 
 @AuraEnabled
 public static list < contact > fetchContact() {
  List < contact > returnConList = new List < contact > ();
 
  List < contact > lstCon = [SELECT id,Name, firstName, LastName, Email, Phone From contact WHERE email != null LIMIT 10];
  // play for loop on lstCon and add each contact to returnConList List.
    for (contact c: lstCon) {
       returnConList.add(c);
    }
 // return the List of contacts
      return returnConList;
 }
 
 
  @AuraEnabled
  public static void sendemail(List<string> ids){
   
      List<Messaging.SingleEmailMessage> mails =  new List<Messaging.SingleEmailMessage>();     
      for(contact cc : [select id,name,Email from contact where ID IN : ids]){
        // 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(cc.Email);
       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 test User'); 
    
    // Step 4. Set email contents - you can use variables!
      mail.setSubject('Contact is Created - Test');
      mail.setHtmlBody('Dear '+ cc.name + ' <br/><br/>New Contact Record is created<br/><br/> Thanks <br/>');
    
    // Step 5. Add your email to the master list
      mails.add(mail);    
      }
     
    // Step 6: Send all emails in the master list
     Messaging.sendEmail(mails);
   }   
    
}
Lightning component :
<aura:component controller="EmailWithCheckboxController" implements="flexipage:availableForAllPageTypes">
   <!--Declare Attributes-->  
   <aura:attribute name="ListOfContact" type="contact[]" />
   <aura:attribute name="selectedCount" type="integer" default="0"/>
   
   <!--aura init handler , call js "loadContactList" function on component load, and display contact data on table-->   
   <aura:handler name="init" value="{!this}" action="{!c.loadContactList}"/>
   <!--Header part-->
   <div class="slds-page-header">
      <p class="slds-page-header__title slds-truncate" title="">Contact List</p>
      <span class="slds-badge">Selected Contact:{!v.selectedCount}</span>
      <div class="slds-grid slds-grid--align-end"> 
         <button class="slds-button slds-button--brand" onclick="{!c.sendMail}">Send Email</button>
      </div>
   </div>
   <!--contacts table part--> 
   <table class="slds-table slds-table--bordered slds-table--cell-buffer">
      <thead>
         <tr class="slds-text-title--caps">
            <th style="width:3.25rem;" class="slds-text-align--right">
               <div class="slds-form-element">
                  <div class="slds-form-element__control">
                     <label class="slds-checkbox">
                        <!--header checkbox for select all-->
                        <ui:inputCheckbox aura:id="box3" change="{!c.selectAll}"/>
                        <span class="slds-checkbox--faux"></span>
                        <span class="slds-form-element__label text"></span>
                     </label>
                  </div>
               </div>
            </th>
            <th>
               <span class="slds-truncate" title="Name">First Name</span>      
            </th>
            <th>
               <span class="slds-truncate" title="Last Name">Last Name</span>
            </th>
            <th>       
               <span class="slds-truncate" title="Email">Email</span>
            </th>
            <th >
               <div class="slds-truncate" title="MobilePhone">Mobile Phone</div>
            </th>
         </tr>
      </thead>
      <!--table body start, 
         Iterate contact list as a <tr>
         -->
      <tbody>
         <aura:iteration items="{!v.ListOfContact}" var="con">
            <tr>
               <td scope="row" class="slds-text-align--right" style="width:3.25rem;">
                  <div class="slds-form-element">
                     <div class="slds-form-element__control">
                        <label class="slds-checkbox">
                           <ui:inputCheckbox text="{!con.Id}" aura:id="boxPack" value="" change="{!c.checkboxSelect}"/>
                           <span class="slds-checkbox--faux"></span>
                           <span class="slds-form-element__label text"></span>
                        </label>
                     </div>
                  </div>
               </td>
               <td scope="row">
                  <div class="slds-truncate" title="{!con.Name}"><a>{!con.Name}</a></div>
               </td>
               <td scope="row">
                  <div class="slds-truncate" title="{!con.LastName}">{!con.LastName}</div>
               </td>
               <td scope="row">
                  <div class="slds-truncate" title="{!con.Email}">{!con.Email}</div>
               </td>
               <td scope="row">
                  <div class="slds-truncate" title="{!con.MobilePhone}">{!con.MobilePhone}</div>
               </td>
            </tr>
         </aura:iteration>
      </tbody>
   </table>
</aura:component>
controller :
({
 loadContactList: function(component, event, helper) {
   // call the helper function for fetch contact from apex class 
     helper.onLoad(component, event);
 },
 
 // For count the selected checkboxes. 
 checkboxSelect: function(component, event, helper) {
   // get the selected checkbox value  
  var selectedRec = event.getSource().get("v.value");
   // get the selectedCount attrbute value(default is 0) for add/less numbers. 
  var getSelectedNumber = component.get("v.selectedCount");
   // check, if selected checkbox value is true then increment getSelectedNumber with 1 
   // else Decrement the getSelectedNumber with 1     
     if (selectedRec == true) {
         getSelectedNumber++;
     } else {
         getSelectedNumber--;
     }
  // set the actual value on selectedCount attribute to show on header part. 
  component.set("v.selectedCount", getSelectedNumber);
 },
 
 // For select all Checkboxes 
 selectAll: function(component, event, helper) {
  //get the header checkbox value  
  var selectedHeaderCheck = event.getSource().get("v.value");
  // get all checkbox on table with "boxPack" aura id (all iterate value have same Id)
  // return the List of all checkboxs element 
  var getAllId = component.find("boxPack");
  // If the local ID is unique[in single record case], find() returns the component. not array   
     if(! Array.isArray(getAllId)){
       if(selectedHeaderCheck == true){ 
          component.find("boxPack").set("v.value", true);
          component.set("v.selectedCount", 1);
       }else{
           component.find("boxPack").set("v.value", false);
           component.set("v.selectedCount", 0);
       }
     }else{
       // check if select all (header checkbox) is true then true all checkboxes on table in a for loop  
       // and set the all selected checkbox length in selectedCount attribute.
       // if value is false then make all checkboxes false in else part with play for loop 
       // and select count as 0 
        if (selectedHeaderCheck == true) {
        for (var i = 0; i < getAllId.length; i++) {
  		  component.find("boxPack")[i].set("v.value", true);
   		 component.set("v.selectedCount", getAllId.length);
        }
        } else {
          for (var i = 0; i < getAllId.length; i++) {
    		component.find("boxPack")[i].set("v.value", false);
   			 component.set("v.selectedCount", 0);
  	    }
       } 
     }  
 
 },
    sendMail: function(component, event, helper) {
        var Ids = [];
        // get all checkboxes 
        var getAllId = component.find("boxPack");
        // If the local ID is unique[in single record case], find() returns the component. not array
        if(! Array.isArray(getAllId)){
            if (getAllId.get("v.value") == true) {
                Ids.push(getAllId.get("v.text"));
            }
        }else{
            // play a for loop and check every checkbox values 
            // if value is checked(true) then add those Id (store in Text attribute on checkbox) in Ids var.
            for (var i = 0; i < getAllId.length; i++) {
                if (getAllId[i].get("v.value") == true) {
                    Ids.push(getAllId[i].get("v.text"));
                }
            }
        } 
        helper.sendHelper(component,event,Ids);
    },
})
helper "
({
    onLoad: function(component, event) {
        console.log('onLoad call');
        //call apex class method
        var action = component.get('c.fetchContact');
        action.setCallback(this, function(response) {
            //store state of response
            var state = response.getState();
            if (state === "SUCCESS") {
                //set response value in ListOfContact attribute on component.
                component.set('v.ListOfContact', response.getReturnValue());
                // set deafult count and select all checkbox value to false on load 
                component.set("v.selectedCount", 0);
                component.find("box3").set("v.value", false);
            }
        });
        $A.enqueueAction(action);
    },
    sendHelper: function(component, event, Ids) {
        // call the server side controller method 	
        var action = component.get("c.sendemail");
        // set the 3 params to sendMailMethod method   
        action.setParams({
            'ids': Ids,
            
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var storeResponse = response.getReturnValue();
                alert('Email send successfully');
            }
            
        });
        $A.enqueueAction(action);
    },
})

for more refernce :
http://sfdcmonkey.com/2017/02/23/delete-multiple-records-using-checkbox-lightning-component/
http://sfdcmonkey.com/2017/01/03/send-email-lightning-component/

Hope it will helps you
Thanks, let us know if it helps you
sfdcmonkey.com

All Answers

sfdcMonkey.comsfdcMonkey.com
HI Thulasi, here is the sample code :

apex class "
public with sharing class EmailWithCheckboxController {
 
 @AuraEnabled
 public static list < contact > fetchContact() {
  List < contact > returnConList = new List < contact > ();
 
  List < contact > lstCon = [SELECT id,Name, firstName, LastName, Email, Phone From contact WHERE email != null LIMIT 10];
  // play for loop on lstCon and add each contact to returnConList List.
    for (contact c: lstCon) {
       returnConList.add(c);
    }
 // return the List of contacts
      return returnConList;
 }
 
 
  @AuraEnabled
  public static void sendemail(List<string> ids){
   
      List<Messaging.SingleEmailMessage> mails =  new List<Messaging.SingleEmailMessage>();     
      for(contact cc : [select id,name,Email from contact where ID IN : ids]){
        // 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(cc.Email);
       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 test User'); 
    
    // Step 4. Set email contents - you can use variables!
      mail.setSubject('Contact is Created - Test');
      mail.setHtmlBody('Dear '+ cc.name + ' <br/><br/>New Contact Record is created<br/><br/> Thanks <br/>');
    
    // Step 5. Add your email to the master list
      mails.add(mail);    
      }
     
    // Step 6: Send all emails in the master list
     Messaging.sendEmail(mails);
   }   
    
}
Lightning component :
<aura:component controller="EmailWithCheckboxController" implements="flexipage:availableForAllPageTypes">
   <!--Declare Attributes-->  
   <aura:attribute name="ListOfContact" type="contact[]" />
   <aura:attribute name="selectedCount" type="integer" default="0"/>
   
   <!--aura init handler , call js "loadContactList" function on component load, and display contact data on table-->   
   <aura:handler name="init" value="{!this}" action="{!c.loadContactList}"/>
   <!--Header part-->
   <div class="slds-page-header">
      <p class="slds-page-header__title slds-truncate" title="">Contact List</p>
      <span class="slds-badge">Selected Contact:{!v.selectedCount}</span>
      <div class="slds-grid slds-grid--align-end"> 
         <button class="slds-button slds-button--brand" onclick="{!c.sendMail}">Send Email</button>
      </div>
   </div>
   <!--contacts table part--> 
   <table class="slds-table slds-table--bordered slds-table--cell-buffer">
      <thead>
         <tr class="slds-text-title--caps">
            <th style="width:3.25rem;" class="slds-text-align--right">
               <div class="slds-form-element">
                  <div class="slds-form-element__control">
                     <label class="slds-checkbox">
                        <!--header checkbox for select all-->
                        <ui:inputCheckbox aura:id="box3" change="{!c.selectAll}"/>
                        <span class="slds-checkbox--faux"></span>
                        <span class="slds-form-element__label text"></span>
                     </label>
                  </div>
               </div>
            </th>
            <th>
               <span class="slds-truncate" title="Name">First Name</span>      
            </th>
            <th>
               <span class="slds-truncate" title="Last Name">Last Name</span>
            </th>
            <th>       
               <span class="slds-truncate" title="Email">Email</span>
            </th>
            <th >
               <div class="slds-truncate" title="MobilePhone">Mobile Phone</div>
            </th>
         </tr>
      </thead>
      <!--table body start, 
         Iterate contact list as a <tr>
         -->
      <tbody>
         <aura:iteration items="{!v.ListOfContact}" var="con">
            <tr>
               <td scope="row" class="slds-text-align--right" style="width:3.25rem;">
                  <div class="slds-form-element">
                     <div class="slds-form-element__control">
                        <label class="slds-checkbox">
                           <ui:inputCheckbox text="{!con.Id}" aura:id="boxPack" value="" change="{!c.checkboxSelect}"/>
                           <span class="slds-checkbox--faux"></span>
                           <span class="slds-form-element__label text"></span>
                        </label>
                     </div>
                  </div>
               </td>
               <td scope="row">
                  <div class="slds-truncate" title="{!con.Name}"><a>{!con.Name}</a></div>
               </td>
               <td scope="row">
                  <div class="slds-truncate" title="{!con.LastName}">{!con.LastName}</div>
               </td>
               <td scope="row">
                  <div class="slds-truncate" title="{!con.Email}">{!con.Email}</div>
               </td>
               <td scope="row">
                  <div class="slds-truncate" title="{!con.MobilePhone}">{!con.MobilePhone}</div>
               </td>
            </tr>
         </aura:iteration>
      </tbody>
   </table>
</aura:component>
controller :
({
 loadContactList: function(component, event, helper) {
   // call the helper function for fetch contact from apex class 
     helper.onLoad(component, event);
 },
 
 // For count the selected checkboxes. 
 checkboxSelect: function(component, event, helper) {
   // get the selected checkbox value  
  var selectedRec = event.getSource().get("v.value");
   // get the selectedCount attrbute value(default is 0) for add/less numbers. 
  var getSelectedNumber = component.get("v.selectedCount");
   // check, if selected checkbox value is true then increment getSelectedNumber with 1 
   // else Decrement the getSelectedNumber with 1     
     if (selectedRec == true) {
         getSelectedNumber++;
     } else {
         getSelectedNumber--;
     }
  // set the actual value on selectedCount attribute to show on header part. 
  component.set("v.selectedCount", getSelectedNumber);
 },
 
 // For select all Checkboxes 
 selectAll: function(component, event, helper) {
  //get the header checkbox value  
  var selectedHeaderCheck = event.getSource().get("v.value");
  // get all checkbox on table with "boxPack" aura id (all iterate value have same Id)
  // return the List of all checkboxs element 
  var getAllId = component.find("boxPack");
  // If the local ID is unique[in single record case], find() returns the component. not array   
     if(! Array.isArray(getAllId)){
       if(selectedHeaderCheck == true){ 
          component.find("boxPack").set("v.value", true);
          component.set("v.selectedCount", 1);
       }else{
           component.find("boxPack").set("v.value", false);
           component.set("v.selectedCount", 0);
       }
     }else{
       // check if select all (header checkbox) is true then true all checkboxes on table in a for loop  
       // and set the all selected checkbox length in selectedCount attribute.
       // if value is false then make all checkboxes false in else part with play for loop 
       // and select count as 0 
        if (selectedHeaderCheck == true) {
        for (var i = 0; i < getAllId.length; i++) {
  		  component.find("boxPack")[i].set("v.value", true);
   		 component.set("v.selectedCount", getAllId.length);
        }
        } else {
          for (var i = 0; i < getAllId.length; i++) {
    		component.find("boxPack")[i].set("v.value", false);
   			 component.set("v.selectedCount", 0);
  	    }
       } 
     }  
 
 },
    sendMail: function(component, event, helper) {
        var Ids = [];
        // get all checkboxes 
        var getAllId = component.find("boxPack");
        // If the local ID is unique[in single record case], find() returns the component. not array
        if(! Array.isArray(getAllId)){
            if (getAllId.get("v.value") == true) {
                Ids.push(getAllId.get("v.text"));
            }
        }else{
            // play a for loop and check every checkbox values 
            // if value is checked(true) then add those Id (store in Text attribute on checkbox) in Ids var.
            for (var i = 0; i < getAllId.length; i++) {
                if (getAllId[i].get("v.value") == true) {
                    Ids.push(getAllId[i].get("v.text"));
                }
            }
        } 
        helper.sendHelper(component,event,Ids);
    },
})
helper "
({
    onLoad: function(component, event) {
        console.log('onLoad call');
        //call apex class method
        var action = component.get('c.fetchContact');
        action.setCallback(this, function(response) {
            //store state of response
            var state = response.getState();
            if (state === "SUCCESS") {
                //set response value in ListOfContact attribute on component.
                component.set('v.ListOfContact', response.getReturnValue());
                // set deafult count and select all checkbox value to false on load 
                component.set("v.selectedCount", 0);
                component.find("box3").set("v.value", false);
            }
        });
        $A.enqueueAction(action);
    },
    sendHelper: function(component, event, Ids) {
        // call the server side controller method 	
        var action = component.get("c.sendemail");
        // set the 3 params to sendMailMethod method   
        action.setParams({
            'ids': Ids,
            
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var storeResponse = response.getReturnValue();
                alert('Email send successfully');
            }
            
        });
        $A.enqueueAction(action);
    },
})

for more refernce :
http://sfdcmonkey.com/2017/02/23/delete-multiple-records-using-checkbox-lightning-component/
http://sfdcmonkey.com/2017/01/03/send-email-lightning-component/

Hope it will helps you
Thanks, let us know if it helps you
sfdcmonkey.com
This was selected as the best answer
Somu SomuSomu Somu
could u please help this
https://developer.salesforce.com/forums#!/feedtype=SINGLE_QUESTION_DETAIL&dc=Developer_Forums&criteria=ALLQUESTIONS&id=9060G0000005RYfQAM
Thulasi ReddysThulasi Reddys
Thanks  piyush_soni