Hello Everyone, In this tutorial, I am providing an example of a Lightning component that helps you to send an email with the entered message to any email address. In this example, I am using apex Messaging class to send the email.
After completing this tutorial, you’ll able to:
- Send email using Lightning component.
So let's start.
Send Email Lightning Component
Step 1: Login to your Salesforce Org. and open developer console.
Step 2: Go to File>New>Apex Class and Create an Apex controller called SendEmailHandler. Replace following code in apex controller.
SendEmailHandler.apxc
Step 3: Go to File>New>Lightning Component and create a Lightning Component called SendEmail. Replace the following markup in the Lightning Component.
SendEmailHandler.apxc
public class SendEmailHandler { @AuraEnabled public static string processEmail(String email, String Subject, String Message){ String sMessage=''; try{ Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {email}; mail.setToAddresses(toAddresses); mail.setSubject(Subject); mail.setHtmlBody(Message); Messaging.SendEmailResult [] results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail}); sMessage='Success'; } catch(Exception ex){ sMessage=ex.getLineNumber()+'\n'+ex.getCause()+'\n'+ex.getMessage()+'\n'+ex.getStackTraceString(); } return sMessage; } }
Step 3: Go to File>New>Lightning Component and create a Lightning Component called SendEmail. Replace the following markup in the Lightning Component.
SendEmail.cmp
<aura:component controller="SendEmailHandler" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" > <aura:handler event="aura:waiting" action="{!c.showSpinner}"/> <aura:handler event="aura:doneWaiting" action="{!c.hideSpinner}"/> <aura:attribute name="Spinner" type="boolean" default="false"/> <aura:attribute name="myMessage" type="String" default=''/> <div class="slds-form-element" style="margin-left:10%;margin-right:10%"> <h1> <center style="font-size:26px;margin-top:10px;"><u>Send Email</u></center> </h1> <label class="slds-form-element__label" for="form-element-01">Email-Id</label> <div class="slds-form-element__control"> <input type="text" id="txtEmail" class="slds-input" /> </div> <label class="slds-form-element__label" for="form-element-01">Subject</label> <div class="slds-form-element__control"> <input type="text" id="txtSubject" class="slds-input" /> </div> <label class="slds-form-element__label" for="form-element-01">Message</label> <div class="slds-form-element__control"> <lightning:inputRichText value="{!v.myMessage}" placeholder="Type something interesting"/> </div> <br/> <lightning:button variant="success" label="Send Email" title="Send Email" onclick="{!c.Send}"/> </div> <aura:if isTrue="{!v.Spinner}"> <div aura:id="spinnerId" class="slds-spinner_container"> <div class="slds-spinner--brand slds-spinner slds-spinner--large slds-is-relative" role="alert"> <span class="slds-assistive-text">Loading</span> <div class="slds-spinner__dot-a"></div> <div class="slds-spinner__dot-b"></div> </div> </div> </aura:if> </aura:component>SendEmailController.js
({ Send : function(component, event, helper) { var email=helper._e('txtEmail').value; var Subject=helper._e('txtSubject').value; var Message=component.get("v.myMessage"); var regExpEmailformat = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if(email==''){ alert('Email-Id is required'); } else if(Subject==''){ alert('Subject is required'); } else if(Message==''){ alert('Message is required'); } else{ if(!email.match(regExpEmailformat)){ alert("Invalid Email Id"); } else{ helper.SendEmail(component); } } }, showSpinner: function(component, event, helper) { component.set("v.Spinner", true); }, hideSpinner : function(component,event,helper){ component.set("v.Spinner", false); }, })SendEmailHelper.js
({ SendEmail : function(component) { var email=this._e('txtEmail').value; var Subject=this._e('txtSubject').value; var Message=component.get("v.myMessage"); var action=component.get("c.processEmail"); action.setParams({ email:email, Subject:Subject, Message:Message }) action.setCallback(this,function(e){ if(e.getState()=='SUCCESS'){ var result=e.getReturnValue(); if(result=='Success'){ alert('Email Send Successfully!'); } else{ alert(result); } } else{ alert(JSON.stringify(e.getError())); } }); $A.enqueueAction(action); }, _e:function(ele){ return document.getElementById(ele); }, })Step 4: Go to File>New>Lightning Application and create a Lightning Application called Preview. Replace the following markup in the Lightning Application.
Preview.app
<aura:application extends="force:slds"> <c:SendEmail/> </aura:application>After that click on Preview button from Right Side Pallete
Output:
See also:
- Global Search Lightning Component
- Set default value in Picklist in Lightning Component
- Delete Lightning Component in Salesforce
Conclusion:
Hope you like this tutorial, for any query or suggestions please feel free to comment.
Thank you.
6 Comments
it is showing error alert saying
ReplyDelete11
null
sendemailfailed:first exception on row 0;firsterror;
STORAGE_LIMIT_EXCEEDED, storage limit exceeded:[]
class.sendemailhandler.processemail:line 11,column 1
Please delete some unused and waste files and document from your Salesforce org.
DeleteGreat work, self explanatory and full of learning.
ReplyDeleteThis helped me a lot, Thank you so much Manish!!
glad to know it helped you. Thank you
DeleteThank you Manish, can you please help me with one extension in this component i.e to include a lookup field for contacts and send the mail to those contacts, will request you to please help!!
Deletehey i will post a blog on this requirement, Please stay with my blog.
ReplyDeletePost a Comment