How to create email / SMS activity using Apex

Records shown as Activities in Salesforce are one of three kinds of sObject:

  • Task (Log a Call, follow-up Tasks)
  • Event (calendar events)
  • EmailMessage + Task (emails)

Additionally, the Task object has a TaskSubtype field, whose value causes Lightning's Activity timeline to display the task as a call, a task, an email, or a list email, with different visual presentation for each subtype. Note that the TaskSubtype field is "creatable", but not "updateable" - you can populate it only upon insert. (The Event object has an EventSubtype field, but it's not used).

So, if all you wish to do is show an entry in the Lightning Activity timeline that is presented as an email, you need simply to insert a Task whose TaskSubtype field is 'Email':

insert new Task(
    Subject = 'Subject: Test email....', 
    WhoId = myContact.Id, 
    WhatId = myOpportunity.Id,
    TaskSubtype = 'Email',
    ActivityDate = Date.today(),
    ...
);

There is no TaskSubtype or sObject for SMS messages, and it's not possible to customize the visual presentation of the Lightning activity timeline. You can, of course, represent them as Task records, and pick which of the four allowed subtypes most fits what you want your users to see and filter by.

Tags:

Apex

Activity