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
Uttpal chandraUttpal chandra 

Custom button for sending Email in Custom Object in Lightning

Hi All,
I had created a one custom object and in that there is one custom field Email id.
I have also created a custom Detail page button So whenever user click on that button it should send Email to that particular email id which is defined in that Custom Object with pdf which contain detail of the current record.

I have to implement this in Lightning.
Best Answer chosen by Uttpal chandra
Khan AnasKhan Anas (Salesforce Developers) 
Hi Uttpal,

Greetings to you!

First, create a visualforce page that renders a PDF.

Visualforce: ConPdfEmailLightning
<apex:page controller="ConPdfEmailLightningC" renderAs="PDF">
    <apex:pageBlock >
        <apex:pageBlockSection columns="1">
            <apex:outputField Value="{!con.FirstName}"/>
            <apex:outputField Value="{!con.LastName}"/>
            <apex:outputField Value="{!con.Email}"/>
            <apex:outputField Value="{!con.Phone}"/>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>

Controller for Visualforce Page: ConPdfEmailLightningC
public class ConPdfEmailLightningC {
    
    public Contact con{get;set;}
    
    public ConPdfEmailLightningC(){
        Id conId = apexpages.currentpage().getparameters().get('id');
        con = [SELECT Id, FirstName, LastName, Phone, Email FROM Contact WHERE Id=: conId];
    }
}

Now, create a lightning component which has one button, on click of this button, it will create send an email with the attached pdf.

Component:
<aura:component controller="ConPdfEmail_SvrC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
	
    <lightning:button variant="brand" label="Send Email" onclick="{!c.sendMail }" />
</aura:component>

Controller:
({
    sendMail : function(component, event, helper) {
        var action = component.get("c.sendMailWithPDF");
        action.setParams({
            'recordId' : component.get('v.recordId'),
        })
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                alert('Email Sent Successfully');
            }
            else if (state === "INCOMPLETE") {
                // do something
            }
                else if (state === "ERROR") {
                    var errors = response.getError();
                    if (errors) {
                        if (errors[0] && errors[0].message) {
                            console.log("Error message: " + 
                                        errors[0].message);
                        }
                    } else {
                        console.log("Unknown error");
                    }
                }
        });
        $A.enqueueAction(action);
    }
})

Apex (Server Side Controller): ConPdfEmail_SvrC
public class ConPdfEmail_SvrC {
    
    @auraEnabled
    public static void sendMailWithPDF(String recordId){
        
        for(Contact cc : [SELECT Id, Name, Email__c FROM Contact WHERE Id =: recordId]){
            Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
            Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
            PageReference pref = page.ConPdfEmailLightning; // Visualforce Page Name
            pref.getParameters().put('Id',recordId);
            pref.setRedirect(true);
            Blob b;
            b = pref.getContent();
            attach.setFileName('ContactDetails.pdf');
            attach.setBody(b);
            semail.setSubject('Contact details');
            List<String> sendTo = new List<String>();
            sendTo.add(cc.Email__c);
            semail.setToAddresses(sendTo);
            semail.setPlainTextBody('Please find the attached contact details');
            semail.setFileAttachments(new Messaging.EmailFileAttachment[]{attach});
            Messaging.sendEmail(new Messaging.SingleEmailMessage[]{semail});
        }
    }    
}

Add this lightning component to Contact's detail page using Lightning App Builder.

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

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi Uttpal,

Greetings to you!

First, create a visualforce page that renders a PDF.

Visualforce: ConPdfEmailLightning
<apex:page controller="ConPdfEmailLightningC" renderAs="PDF">
    <apex:pageBlock >
        <apex:pageBlockSection columns="1">
            <apex:outputField Value="{!con.FirstName}"/>
            <apex:outputField Value="{!con.LastName}"/>
            <apex:outputField Value="{!con.Email}"/>
            <apex:outputField Value="{!con.Phone}"/>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:page>

Controller for Visualforce Page: ConPdfEmailLightningC
public class ConPdfEmailLightningC {
    
    public Contact con{get;set;}
    
    public ConPdfEmailLightningC(){
        Id conId = apexpages.currentpage().getparameters().get('id');
        con = [SELECT Id, FirstName, LastName, Phone, Email FROM Contact WHERE Id=: conId];
    }
}

Now, create a lightning component which has one button, on click of this button, it will create send an email with the attached pdf.

Component:
<aura:component controller="ConPdfEmail_SvrC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
	
    <lightning:button variant="brand" label="Send Email" onclick="{!c.sendMail }" />
</aura:component>

Controller:
({
    sendMail : function(component, event, helper) {
        var action = component.get("c.sendMailWithPDF");
        action.setParams({
            'recordId' : component.get('v.recordId'),
        })
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                alert('Email Sent Successfully');
            }
            else if (state === "INCOMPLETE") {
                // do something
            }
                else if (state === "ERROR") {
                    var errors = response.getError();
                    if (errors) {
                        if (errors[0] && errors[0].message) {
                            console.log("Error message: " + 
                                        errors[0].message);
                        }
                    } else {
                        console.log("Unknown error");
                    }
                }
        });
        $A.enqueueAction(action);
    }
})

Apex (Server Side Controller): ConPdfEmail_SvrC
public class ConPdfEmail_SvrC {
    
    @auraEnabled
    public static void sendMailWithPDF(String recordId){
        
        for(Contact cc : [SELECT Id, Name, Email__c FROM Contact WHERE Id =: recordId]){
            Messaging.SingleEmailMessage semail = new Messaging.SingleEmailMessage();
            Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
            PageReference pref = page.ConPdfEmailLightning; // Visualforce Page Name
            pref.getParameters().put('Id',recordId);
            pref.setRedirect(true);
            Blob b;
            b = pref.getContent();
            attach.setFileName('ContactDetails.pdf');
            attach.setBody(b);
            semail.setSubject('Contact details');
            List<String> sendTo = new List<String>();
            sendTo.add(cc.Email__c);
            semail.setToAddresses(sendTo);
            semail.setPlainTextBody('Please find the attached contact details');
            semail.setFileAttachments(new Messaging.EmailFileAttachment[]{attach});
            Messaging.sendEmail(new Messaging.SingleEmailMessage[]{semail});
        }
    }    
}

Add this lightning component to Contact's detail page using Lightning App Builder.

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
This was selected as the best answer
Ajay K DubediAjay K Dubedi
Hi Uttpal,
As far as I understand your problem you need to implement the following steps to achieve your objective:
1.  Firstly you need a home page to display all your records relating to that custom object with corresponding button. You will be needing lightning datatable to implement this. Refer:  https://developer.salesforce.com/docs/component-library/bundle/lightning:datatable/example AND https://developer.salesforce.com/docs/component-library/bundle/lightning:button

2. Now on click of the button, you need to get the corresponding email id of the element for which you'll need a controller(in JavaScript ) in which do the following let a = e.getSource().get('v.value'); (ensure that you mentioned value attribute )                              <lightning:button value="{!ObjectIdgoes here}" variant="brand" label="Open details" title="Deatils" onclick="{!c.sendmailcontroller}" iconName="utility:preview"/>

3. Now you just need to fetch value and send it to apex class where you'll use Messaging class to send mail, refer: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_single.htm

Hope this helps. If you require any further assistance please let me know. If it does help please mark it as best answer to help others too.
Thanks and Regards,
Ajay Dubedi
Uttpal chandraUttpal chandra
Hi,
I have implemented this and it is working also but it is opening the Pop up whenever i click on it. any idea how to resolve it.
I want to place it beside standard buttons(Edit,Clone etc.). 

User-added image
Khan AnasKhan Anas (Salesforce Developers) 
Hi Uttpal,

If you want to place it beside standard buttons, you need to create quick action. To create quick action, Go to Object Manager -> Contact -> Buttons, Links, and Actions -> New Action -> Select Lightning Component in Action Type -> Select your Lightning Component

After that add it to page layout. Page Layouts -> Mobile and Lightning Actions -> Drag it to Salesforce Mobile and Lightning Experience Actions section.

But it will open a modal popup as this is the standard functionality for lightning quick action. You can not suppress the modal. However, you can close this quick action after you click on Send Email Button. You can add below line of code in your lightning component javaScript.

$A.get("e.force:closeQuickAction").fire();
 
({
    sendMail : function(component, event, helper) {
        var action = component.get("c.sendMailWithPDF");
        action.setParams({
            'recordId' : component.get('v.recordId'),
        })
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                alert('Email Sent Successfully');
                $A.get("e.force:closeQuickAction").fire();
            }
            else if (state === "INCOMPLETE") {
                // do something
            }
                else if (state === "ERROR") {
                    var errors = response.getError();
                    if (errors) {
                        if (errors[0] && errors[0].message) {
                            console.log("Error message: " + 
                                        errors[0].message);
                        }
                    } else {
                        console.log("Unknown error");
                    }
                }
        });
        $A.enqueueAction(action);
    }
})

However, if you place this lightning component directly on detail page using lightning app builder, then the popup will not show up. I have checked and it is working fine for me.

Regards,
Khan Anas