+ Start a Discussion
sesha boddapatisesha boddapati 

send email functionality in lwc

Hi All,

Any one can you please help me , how to write send email functionality in lightning web components


Thanks, sesha.
Gian Piere VallejosGian Piere Vallejos
You can call the event sendEmailAfterEvent from a button in the HTML file. There you can call a method from a Controller to send the email.

Javascript file: 
import { LightningElement, api, wire, track } from 'lwc';
import sendEmailToController from '@salesforce/apex/ControllerLwcExample.sendEmailToController'

export default class LwcExample extends LightningElement {
    @track subject = 'Test Email'
    @track body = 'Hello'
    @track toSend = 'abc@gmail.com'

    sendEmailAfterEvent(){
        const recordInput = {body: this.body, toSend: this.toSend, subject: this.subject}  //You can send parameters
        sendEmailToController(recordInput)
        .then( () => {
            //If response is ok
        }).catch( error => {
            //If there is an error on response
        })

    }
}

ControllerLwcExample.cls file: 
public with sharing class ControllerLwcExample {
    @AuraEnabled(cacheable=true)
    public static void sendEmailToController(String body, String toSend, String subject){
        try{
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[] {toSend};
            mail.setToAddresses(toAddresses);
            mail.setSubject(subject);
            mail.setHtmlBody('<h1>'+ body + '</h1>');
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        }catch(Exception ex){
            throw new AuraHandledException(ex.getMessage());
        }
    }
}

Reference to send the e-mail: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_forcecom_email_outbound.htm
Pushkar GauravPushkar Gaurav
Can you please write test class for the above class?