Automatic Email Template Selection in Case Feed

Specifying default values, based on certain criteria, when sending an email message from the Case Activity Feed sounds like a pretty standard requirement. However, for some reason, I struggled a bit with finding a solution to this problem, so I decided to document it here.

Requirements

My requirements were to automatically preselect a ValidatedFromAddress field and an Email Template when an Agent opens the standard email composer widget (i.e. Send Email Quick Action) in the Case Activity Feed. The field and the template needed to be dynamically preselected based on certain fields on a Case record - for simplicity, let’s call this field Type.

When I heard the above requirements I immediately had a couple of coding solutions in my head that “had to work” in case everything else fails, but as always, I decided to put them aside initially and to first consult my good friend Google. I wanted to see if anyone already invented this wheel, or even better if there’s a standard Salesforce approach to this that will save me the headache of too much maintenance in the future.

Salesforce Documentation (and attempts that failed)

So I started googling and I immediately found this documentation. Not a bad solution, however, it’s not dynamic.

Second (or more like N-th) attempt returned me this document. OK, that looks promising, even though it involves the creation of an Apex class, but I’m a developer so I can live with that - heck, I’ll even enjoy it.

I started implementing this solution and was really puzzled when it didn’t work. Why? Because I missed to read the fine print that said Available in: Salesforce Classic, but not in Lightning, and I needed this to work in Lightning. Nonetheless, I was happy for this exercise, as it turned out that it held a key for making my 3rd attempt a success.

Finally, on my third attempt, I somehow stumbled upon this interface called QuickActionDefaultsHandler. Here’s the quick excerpt from its documentation:

The QuickAction.QuickActionDefaultsHandler interface lets you specify the default values for the standard Email and Send Email actions in the case feed. You can use this interface to specify the From address, CC address, BCC address, subject, and email body for the Email action in the case feed. You can use the interface to pre-populate these fields based on the context where the action is displayed, such as the case origin (for example, country) and subject.

Perfect, exactly what I need. I just hope it works in Lightning.

A Simplified Working Solution

First, create a class - I called mine EmailTemplateSelector. Salesforce documentation already holds quite a few useful examples of its implementation, but here’s my simplified example below:

global class EmailTemplateSelector implements QuickAction.QuickActionDefaultsHandler {
  global EmailTemplateSelector() { }

  global void onInitDefaults(QuickAction.QuickActionDefaults[] defaultsList) {
    for (Integer j = 0; j < defaultsList.size(); j++) {
      QuickAction.QuickActionDefaults defaults = defaultsList.get(j);

      // Check if the quick action is the standard case feed `SendEmail` action
      if (
        defaults instanceof QuickAction.SendEmailQuickActionDefaults &&
        defaults.getTargetSObject().getSObjectType() == EmailMessage.sObjectType &&
        defaults.getActionType().equals('SendEmail')
      ) {
        String actionName = defaults.getActionName();
        Id contextId = defaults.getContextId();

        // check if the related object is a Case
        // and process it in the same way no matter if it's 
        // a `SendEmail`, `Reply`, or `Reply All` action
        if (
          (actionName.equals('Case.SendEmail') ||
           actionName.equals('EmailMessage._Reply') ||
           actionName.equals('EmailMessage._ReplyAll')) &&
           contextId != null &&
           contextId.getSobjectType() == Case.sObjectType
        ) {
          applySendEmailDefaultsForCase((QuickAction.SendEmailQuickActionDefaults) defaults);
          break;
        }
      }
    }
  }

  private void applySendEmailDefaultsForCase(QuickAction.SendEmailQuickActionDefaults sendEmailDefaults) {
    // query for the relevant data on the related Case record (e.g. Type field)
    Case c = [
      SELECT Type
      FROM Case
      WHERE Id = :sendEmailDefaults.getContextId()
    ];

    // implement some logic to obtain the correct `emailTemplateId` && `validatedFromAddress`,
    // based on the Case record fields (preferably using a Custom Metadata Type)
        
    // apply the default email template
    sendEmailDefaults.setTemplateId(emailTemplateId);
    sendEmailDefaults.setInsertTemplateBody(true);
    sendEmailDefaults.setIgnoreTemplateSubject(false);

    // apply other field defaults to EmailMessage (e.g. ValidatedFromAddress)
    EmailMessage emailMessage = (EmailMessage) sendEmailDefaults.getTargetSObject();
    emailMessage.ValidatedFromAddress = validatedFromAddress;
  }
}

I haven’t provided the exact way to obtain the emailTemplateId and validatedFromAddress values, as this depends on your specific requirements. However, I will just say that you can query Email Templates using a query similar to the one below:

SELECT Id FROM EmailTemplate WHERE DeveloperName = 'SAMPLE_NAME'

Salesforce documentation doesn’t mention this, but the above implementation will not work if you just create a class and implement the above interface. As it stands, the above class is not invoked at all when you open the Email Quick Action. However, there’s another document that I went through by chance (during my second attempt) before implementing the above logic, that mentioned the following steps:

  1. From Setup, enter Support Settings in the Quick Find box, then select Support Settings.
  2. Click Edit.
  3. Select Enable default email templates.
  4. Choose the Apex class that contains your template selection logic.
  5. Click Save.

So after we follow the above steps, our Support Settings should look like this:

supportSettings

Now the EmailTemplateSelector class will finally get invoked when you open the email composer widget in Case Activity Feed, and the email template will get prepopulated correctly.

Extending the current solution with a Custom Metadata Type

The above solution is fine as it is, but I would like to suggest a further exercise to make yours, and the life of your admins, easier.

I suggest creating a Custom Metadata Type called, for example, Email Template Mapping. There you can create fields to declaratively define different conditions upon which a different email template and EmailMessage fields are set. This will allow admins to change this logic without involving a developer.

Written on November 24, 2019