[SalesForce] Task Workflow to send email to Who (Lead or Contact)

I have a situation where I want a certain type of Task to trigger an email alert to the "Who" Contact or Lead that the task is related to. In the Spring '16 release Salesforce added the ability to send Email Alerts on Task workflows, which is great, but I can't seem to make it send to the related Lead or Contact – they don't come up as options for the Recipient.

Has anyone found a workaround to this?

Best Answer

Try this:

  1. Create a custom Activity field Email__c of type Email
  2. Populate it with the trigger below
  3. You now have an email field available to the Email Alert

    trigger TaskTrigger on Task (before insert, before update) {
      set<ID> lIdSet = new set<ID>();
      set<ID> cIdSet = new set<ID>();
      for (Task t : Trigger.new)  // collect parentIds
         if (t.whoId == null) {}
         else
         if (t.whoId.getSobjectType() == Lead.SObjectType)
            lIdSet.add(t.whoId);
         else
         if (t.whoId.getSobjectType() == Contact.SObjectType)
            cIdSet.add(t.whoId);
    
      // Find the parents
      map<ID,Lead> lIdToLeadMap = new map<ID,Lead>([select id, email 
                                                        from Lead where id IN :lIdSet]);
      map<ID,Contact> cIdToContactMap = new map<ID,Contact>([select id, email 
                                                        from Contact where id IN :cIdSet]);
    
      // now populate the custom email__c field from parent
      for (Task t: Trigger.new) 
        t.email__c = lIdToLeadMap.containsKey(t.whoId)
           ? lIdToLeadMap.get(t.whoId).email
           : cIdToContactMap.containsKey(t.whoId)
               ? cIdToContactMap.get(t.whoId).email
               : null; 
    
      // since this is a before trigger, changing value of Trigger.new members implicitly updates the database
    }
    
Related Topic