Sending Email Notification for Task Owner via Apex Trigger

I have this business requirement which is when a Salesforce record is inserted and has this specific status, it will auto-create a task and notify the assigned owner via email that he has a new task. So I’ve written a trigger to automate it, during testing I saw that the task has been created and it properly assigns the user until I noticed that it’s not actually sending a notification email unlike when you create a task manually using the standard UI.

I consulted Mr. Google and I stumbled upon this 2-year old developer forum post which discusses the same issue, I tried out the sample code and it seems to work correctly.

For simplicity’s sake, I will be using the standard Opportunity object for the sample code.

Here’s the code snippet:

Trigger:

trigger OpportunityTrigger on Opportunity (before insert, before update, after insert, after update) 
{
   if(trigger.isAfter)
   { 
      if(trigger.isInsert)
      {
         // TriggerHelper is a separate utility class where you can store your static variables 
         // This is used to prevent trigger recursions when there are workflow updates
         if(TriggerHelper.bAfterInsertRun == null) 
         {
            OpportunityHandler.createTask(trigger.new);
            TriggerHelper.bAfterInsertRun = true; // flag the static variable so that it will execute this block of code only once
         }
      }
   }
 ...
}

Class Handler:

public without sharing OpportunityHandler
{
    public static void createTask(List triggerNew)
    {
       List listTasksToInsert = new List();
 
       for(Opportunity objOppty: triggerNew)
       {
           if(objOppty.StageName == 'Follow Up')
           {
              Task newTask = new Task();
              newTask.WhatId = objOppty.Id;
              newTask.Type = 'Follow Up';
              newTask.Description = 'Please follow up this opportunity';
              newTask.Priority = 'Normal';
              newTask.IsReminderSet = true;
              newTask.ReminderDateTime = System.now().addHours(2);
              newTask.Status = 'Not Started';
              newTask.Subject = 'You have a task';
              newTask.ActivityDate = date.Today(); //Due Date
              newTask.OwnerId = Userinfo.getUserId();
              listTasksToInsert.add(newTask);
           }
        }
 
        try 
        {
            if(listTasksToInsert.size() < 0)
            {
               List listInsertedTaskIds = new List();
 
               Database.SaveResult[] srList = Database.insert(listTasksToInsert, false);
 
               for(Database.SaveResult sr: srList)
               {
                  if(sr.isSuccess())
                  {
                     listInsertedTaskIds.add(sr.getId());
                  }
               } 
               triggerTaskNotification(listInsertedTaskIds); 
           }
       } 
       catch(DMLException ex)
       {
          system.debug('error : ' + ex.getMessage());
       }
    }
 
    // Mark this method as a future call to prevent it from sending the email twice
    @future 
    public static void triggerTaskNotification(List taskIds)
    {
       List taskClone = [Select Id From Task Where Id=:taskIds];
       //Set EmailHeader.triggerUserEmail to true
       Database.DMLOptions dmlo = new Database.DMLOptions();
       dmlo.EmailHeader.triggerUserEmail = true; 
       System.debug('##taskClone: ' + taskClone); 
       //Update Task 
       database.update(taskClone, dmlo);
    }
}

Feel free to comment if it does work or not. 🙂

Leave a comment

Your email address will not be published. Required fields are marked *