Call Apex Method from Process to Send an Email

In this post, we will implement the functionality to call an Apex method from Process to send an Email from Apex. We can use Email Alert with Process to send an Email with only Configuration but there are some restrictions with Email Alerts like:

  1. Email Alerts have limited set of Recipients.
  2. If we use Email Alert to send an Email, we have to create and manage Email Alert for every Email Template that we create.

In this post, we wil create a Dynamic Apex Class that will send emails based on the parameters sent by Process. In this way, we can have multiple Processes based on Business requirement that will call the same Apex Class. Single Apex class will take care of sending all the Emails. Let’s get into the implementation.

Implementation

In this implementation, we will create an Email Template. Once the Contact record is created, we will call the Apex method from Process that will send an Email.

Email Template

First, create a Custom Email Template.

  1. Type Email Template in Quick Find box and click on Classical Email Templates.
  2. Select the Type of Email Template and click Next.
  3. Enter the required fields and click Next.
  4. Enter the Subject and Html Body for your Email Template and click Next.
  5. Keep the Text Body as blank and click Save.

Below is the preview of Welcome Email Template created.

Email Template in Salesforce
Email Template in Salesforce

Welcome Email

Subject: Welcome to Niks Developer Blog

Hi {!Account.Name},
<br/><br/>
Welcome to the Niks Developer Blog. I hope you learnt something today.
<br/><br/>
Thanks, <br/>
Niks Developer

Send Email from Apex

Next step is to create a Dynamic Apex Class. To call a Apex method from Process, we have to declare a method as Invocable by adding @InvocableMethod annotation. We can only pass the one parameter to this method. The type of parameter must be List of either Primitive, SObjets or user defined type. The Class should be either Public or Global. Please check this link to know more about Invocable Method.

First, we have to create a Wrapper class EmailWrapper to send the parameters from the Process. The variables in the wrapper must be annotated with @InvocableVariable annotation.

EmailWrapper.apxc

public class EmailWrapper {
    @InvocableVariable public String strEmailTemplate;
    @InvocableVariable public String strRecipientId;
    @InvocableVariable public String strRecipientEmail;
}

Then, Create Apex class EmailController and add sendWelcomeEmail Invocable Method which accepts the list of EmailWrapper.

  • Create an instance of Messaging.SingleEmailMessage and use setToAddresses() to set To Address.
  • Use setTemplateId() method to set Template Id that can be queried by using the strEmailTemplate passed from Process.
  • Use setTargetObjectId() method to provide the Contact Id that will be used to provide the values for Merge Fields. For Example, Hi {!Contact.Name} in the Email Templaet will be replaced by Hi Nikhil Palekar if the Name of Contact provided is Nikhil Palekar.
  • Use setTreatTargetObjectAsRecipient(false) with false parameter as we are not using Target Object i.e, Contact as a Recipient. We can set it as true if we want to send the Email to Email field of the Contact provided. We are keeping it false becasue we want to pass the To address from Process to make it more dynamic.
  • You can also use setOrgWideEmailAddressId(emailAddressId) to set the From Address.
  • Use Messaging.sendEmail() to send the Email. Pass SingleEmailMessage instance we created earlier as a parameter to this method.

EmailController.apxc

public class EmailController {
    
    @InvocableMethod
    public static void sendWelcomeEmail(list<EmailWrapper> lstEmailWrapper){
		Messaging.SingleEmailMessage objEmail = new Messaging.SingleEmailMessage();
        
        // Set the Email of the Recipient.
        objEmail.setToAddresses(new list<String>{lstEmailWrapper[0].strRecipientEmail});
		
        // Set the Template Id
        objEmail.setTemplateId([SELECT Name FROM EmailTemplate WHERE Name = :lstEmailWrapper[0].strEmailTemplate LIMIT 1].Id);
        
        // To set the context and ensures that merge fields in the template contain the correct data.
        objEmail.setTargetObjectId(lstEmailWrapper[0].strRecipientId);
        objEmail.setTreatTargetObjectAsRecipient(false);
        
        Messaging.SendEmailResult[] emailResult = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {objEmail});
        if(!emailResult[0].isSuccess()){
            System.debug('Error :' +emailResult[0].getErrors());
        } else{
            System.debug('Success');
        } 
    }
}

Call Apex Method from Process

Finally, we have to create a Process.

  • Type Process Builder in Quick Find box and click on Process Builder.
  • Click on New. Enter Process Name. For The process starts when, select A record changes.
  • Then, click on Add Object and select Contact. For Start the Process, select only when a record is created and click Save.
  • Click on Add Criteria, and enter Criteria Name. Enter the Criteria to check if Email of the Contact is not Null.

Criteria for Process
Criteria for Process

Add the Immediate Action for this Criteria.

  • Click on Add Action and select Apex as Action Type.
  • Enter the Action Name and Select EmailController as Apex Class.
  • Click on Add Row. Select strRecipientId Field and pass Id of the Contact. For strRecipientEmail, pass Email of the Contact. For strEmailTemplate, pass name of the Email Template we created earlier.
  • Click on Save and Activate the Process.
Send Email from Apex
Send Email from Apex

Call Apex Method from Process to Send an Email

This is pretty much it. To test this, Create a Contact and provide an Email address. A Welcome Email will be sent to the Email address provided.

Call Apex Method from Process
Call Apex Method from Process

You can create multiple Processes based on the requirement to send Emails. You just need to pass the To Address, Email Template Name and Id of the Target Object to fill the Merge fields.

This is how we can Call Apex Method from Process to Send an Email. If you want to check more such implementaions by Configuration, you can check it here.

If you don’t want to miss new implementations, please Subscribe here.

2 thoughts on “Call Apex Method from Process to Send an Email”

  1. Hi Nikhil
    Can you clarify the below statement

    We can use Email Alert with Process to send an Email with only Configuration but there are some restrictions with Email Alerts like

    Do you meant to say send email alert with WORKFLOW RULES as I think we cannot send alerts using process builder.

    is the above code holds good for bulk contacts insert through Data Import Wizard. Say it has 100 contacts is it going to run 100 instances of process builder which in turn will run Apex. If my understanding is correct, then is it really needed to pass list of EmailWrapper?

    1. 1. We can use Email Alerts as Immediate Action in Process using Process Builder as well. 2. For Bulk operations, Process Builder is already optimized and bulkified. It’s better to keep batch size low in case of bulk creation to avoid any governor limits. 3. Invocable Method only accepts list of records as its “only” parameter.

Comments are closed.