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
The new LearnerThe new Learner 

how to send an email using lwc

Hi Experts, 
 
Need to send a mass email to selected contacts, just like send list email button using lwc. can anyone help me out
Best Answer chosen by The new Learner
mukesh guptamukesh gupta
Hi ,

Yes, you can add quick action on All contact pages, Please use below code:-


sendMassEmail.js-meta.xml
 
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
 <targets>

        <target>lightning__RecordAction</target>

    </targets>

    <targetConfigs>

        <targetConfig targets=”lightning__RecordAction”>

            <actionType>ScreenAction</actionType>

        </targetConfig>

    </targetConfigs>
</LightningComponentBundle>

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh​​​​​​​

All Answers

CharuDuttCharuDutt
Hii New Learner
Try Below Code
HTML:
<template>
<lightning-card  variant="Narrow"  title="Hello" icon-name="standard:account">
    <lightning-button variant="base" label="send Email" onclick={handleClick}></lightning-button>

    <lightning-datatable
    data={data}
    columns={column}
    key-field="id"
    onrowselection={getSelectedName}
>
</lightning-datatable>
</lightning-card>
</template>


JS:
import { LightningElement,wire } from 'lwc';
import getaccrecordstodisplay from '@salesforce/apex/SendEmailFromLWC.getaccrecordstodisplay';
import SendEmail from '@salesforce/apex/SendEmailFromLWC.SendEmail';
const columns = [
    { label: 'Id', fieldName: 'Id', type: 'text' },
    { label: 'Name', fieldName: 'Name', type: 'text' },
    { label: 'Email', fieldName: 'Email'}
];
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
export default class SendEmialFromLWC extends LightningElement {
    data;
    error;
    listOfEmail = [];
    column = columns;

    @wire(getaccrecordstodisplay)
    wiredClass({data, error}) {
        if(data) {
           
            this.data = data; 
               
        }
        else if(error) {
           this.error = error;
           this.data = undefined;
        }
    }

    getSelectedName(event) {
        const selectedRows = event.detail.selectedRows;
        
        for (let i = 0; i < selectedRows.length; i++) {
            alert('You selected: ' + selectedRows[i].Email);
            this.listOfEmail.push(selectedRows[i].Email);
            alert('List>>>>> '+ this.listOfEmail);
        }
    }

    handleClick(){
        const selectedEmails = this.listOfEmail;
        SendEmail({
            EmailList: selectedEmails
        })
        .then(result =>{
            var toast = new ShowToastEvent({
            'title': 'Successfull',
            'message': 'Email Sent Successfully',
            'variant': 'success'
        });
        this.dispatchEvent(toast);
        }).catch(error =>{
            Console.log(error);
        })
    }
}



APEX:
public class SendEmailFromLWC {
 	@AuraEnabled(cacheable = true)
    public static List<Contact> getaccrecordstodisplay(){
       return [select ID,Name,Email from Contact limit 10];
    }
     @AuraEnabled(cacheable = true)
    public static void SendEmail(List<String> EmailList){
         Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
       
        mail.setToAddresses(EmailList);
        mail.setSubject('Testing Emails');
        mail.setPlainTextBody('Dear Contact,please ready to contact if you have any issues');
        
        
        Messaging.SendEmailResult[] results = Messaging.sendEmail(
                                 new Messaging.SingleEmailMessage[] { mail });
    }
}
Pease Mark It As Best Answer If It Helps
Thank You!
mukesh guptamukesh gupta
Hi Learner,


I have added this component to Account record page,  but you can add according your requirment like link with Quick action etc

User-added image
You can use below code :-

sendMassEmail.html

 
<template>
 
    <lightning-card  variant="Narrow"  title="Contact List" icon-name="standard:contact">
     <lightning-button variant="Neutral" label="Send Email" onclick={handleClick}></lightning-button>
     
 
        <lightning-datatable
        data={data}
        columns={column}
        key-field="id"
        onrowselection={getSelectedName}
    >
    </lightning-datatable>

    </lightning-card>
    </template>

sendMassEmail.js
 
import { LightningElement,wire } from 'lwc';
import getContactList from '@salesforce/apex/SendMassEmail.getContactRecords';
import sendEmailToContact from '@salesforce/apex/SendMassEmail.sendEmails';
const columns = [
    { label: 'Id', fieldName: 'Id', type: 'text' },
    { label: 'Name', fieldName: 'Name', type: 'text' },
    { label: 'Email', fieldName: 'Email'}
];
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
export default class SendMassEmail extends LightningElement {
    data;
    error;
    listOfContacts = [];
    column = columns;

    @wire(getContactList)
    wiredClass({data, error}) {
        if(data) {
          
            this.data = data; 
               
        }
        else if(error) {
           this.error = error;
           this.data = undefined;
        }
    }

    getSelectedName(event) {
        const selectedRows = event.detail.selectedRows;
        
        for (let i = 0; i < selectedRows.length; i++) {
            this.listOfContacts.push(selectedRows[i].Id);
        }
    }

    handleClick(){
        //const selectedContacts = this.listOfContacts;

        alert(this.listOfContacts)
        //console.log('selectedContacts--- '+this.listOfContacts);
        sendEmailToContact({
            ConList: this.listOfContacts
        })
        .then(result =>{
            var toast = new ShowToastEvent({
            'title': 'Successfull',
            'message': 'Email Sent Successfully',
            'variant': 'success'
        });
        this.dispatchEvent(toast);
        }).catch(error =>{
            console.log(error);
        })
    }
}


sendMassEmail.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>

     <targets>
      <target>lightning__RecordPage</target>
      <target>lightning__AppPage</target>
      <target>lightning__HomePage</target>
  </targets>
  <targetConfigs>
      <targetConfig targets="lightning__RecordPage">
          <objects>
              <object>Account</object>
             
          </objects>
      </targetConfig>
    
  </targetConfigs>
</LightningComponentBundle>

SendMassEmail​​​​​​​.cls
 
public with sharing class SendMassEmail {

    @AuraEnabled(cacheable = true)
    public static List<Contact> getContactRecords(){
       return [select ID,Name,Email from Contact Where Email != '' limit 20];
    }

    @AuraEnabled(cacheable = true)
    public static void sendEmails(List<String> ConList){
         // Step 0: Create a master list to hold the emails we'll send
        List<Messaging.SingleEmailMessage> mails =   new List<Messaging.SingleEmailMessage>();
		For(Contact con : [Select Id, FirstName, Email from Contact where Id IN: ConList]){

            Messaging.SingleEmailMessage mail =  new Messaging.SingleEmailMessage();
          
            // Step 1: Set list of people who should get the email
            List<String> sendTo = new List<String>();
            sendTo.add(con.Email);
            mail.setToAddresses(sendTo);
          
            mail.setSenderDisplayName('Official Bank of Notification');
          
          // Step 3. Set email contents - you can use variables!
            mail.setSubject('URGENT BUSINESS PROPOSAL');
            String body = 'Dear ' + con.FirstName + ', ';
            body += 'Please update your permanent address.';
            body += 'our sales person getting diffecultis to found your address';
            
            mail.setHtmlBody(body);
            mails.add(mail);

        }
         // Step 4: Send all emails in the master list

		if(mails.size() > 0) {
            try{
                Messaging.sendEmail(mails);
            }catch(exception e){
                System.debug('getMessage-->>>>>> '+e.getMessage());
               // apexpages.addmessage(new apexpages.message(apexpages.severity.error,e.getMessage()));
            }   
        }
           
           
    }
}

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh​​​​​​​

 
The new LearnerThe new Learner
Hi Mukuesh,

Cant I add this quick action to all contact page instead of single record using action , more its opening that page to add email template. can you help me on that
mukesh guptamukesh gupta
Hi ,

Yes, you can add quick action on All contact pages, Please use below code:-


sendMassEmail.js-meta.xml
 
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
 <targets>

        <target>lightning__RecordAction</target>

    </targets>

    <targetConfigs>

        <targetConfig targets=”lightning__RecordAction”>

            <actionType>ScreenAction</actionType>

        </targetConfig>

    </targetConfigs>
</LightningComponentBundle>

if you need any assistanse, Please let me know!!

Kindly mark my solution as the best answer if it helps you.

Thanks
Mukesh​​​​​​​
This was selected as the best answer