Play Games

Search This Blog

Tuesday, September 26, 2017

How to send email through a custom button on record detail page salesforce

In this example, We are considering sending Email through lead record detail page.

Note: 1) Subject__C custom field is created in  lead object to store the subject of Email.

2) Standard Email field is used to store email address to which email will be sent.
Standard Description field is used to store content/body of Email.

3) Email and Description are mandatory fields in order to send an Email.

Step 1: Create an Apex Class:
public class SendEmailFromLeadController {
    public String emailSent {get;set;}
    public SendEmailFromLeadController(ApexPages.StandardController controller) {
   
    }

    public PageReference sendEmail() {
        emailSent ='';
        List<lead> lstLead = [ select Name,id,description,subject__c,Email FROM lead  WHERE id = :ApexPages.currentPage().getParameters().get('id')];
        emailSent = ApexPages.currentPage().getParameters().get('emailSent');
        PageReference pageRef ;
        if(emailSent == null || emailSent =='') {
            list<Messaging.SingleEmailMessage> lstEmail = new list<Messaging.SingleEmailMessage>();
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setTargetObjectId(lstLead[0].Id);
            mail.setToAddresses(new List<String>{lstLead[0].Email});
            mail.SetSubject(lstLead[0].subject__c);
            mail.setPlainTextBody(lstLead[0].description);
            lstEmail.add(mail);
            list<Messaging.SendEmailResult> lstResults = Messaging.sendEmail(lstEmail);
            if(lstResults[0].isSuccess()) {
                emailSent = 'Email Successfully Sent';
                pageRef = New PageReference('/apex/SendEmailFromLead?emailSent='+'Email Successfully Sent');
            } else {
                emailSent = 'Email Not Sent';
                pageRef = New PageReference('/apex/SendEmailFromLead?emailSent='+'Email Not Sent');
            }
            pageRef.setRedirect(true);
        } else {
            pageRef = null;
        }
       
        return pageRef ;
    }

}

Step 2: Create visualforce Page - PageName : SendEmailFromLead
<apex:page standardcontroller="lead" extensions="SendEmailFromLeadController" action="{!sendEmail}">
<apex:form >
 <b style="color:red">{!emailSent}</b>
</apex:form>
</apex:page>

Step 3: Create custom Button on lead object for example like this

Thats it...Go to Lead Record..Enter email,description,subject fields and then click 'Send Email' button to send an email .Enjoy...

No comments:

Post a Comment