Salesforce Apex: Send Notification when Task Created From Apex

Sometimes, we would want to create a list of tasks and assign them to users automatically in Apex. And, the assignees should get a notification that a task has been assigned to them. However, in apex class, there is nothing call “Notify Assignee” checkbox like what you see in the Task Workflow Action as shown below.



A quick workaround for this is you can turn on the triggerUserEmail DML option when creating the Task. For example:


List myTasks = new List();
for(integer i = 0; i < 5; i ++){
    Task newTask = new Task();
    newTask.Subject='Automated Task';
    newTask.OwnerId = ;
Database.DMLOptions notifyOption = new Database.DMLOptions();
notifyOption.EmailHeader.triggerUserEmail = true;

//we need to use the Database.insert() with the DMLOptions to insert the task instead of using the standard insert DML command
Database.insert(newTask, notifyOption);