Skip to content

Instantly share code, notes, and snippets.

@supercargo
Last active October 14, 2021 23:26
Show Gist options
  • Save supercargo/56844009ccf890a1f0763e2589ab89bd to your computer and use it in GitHub Desktop.
Save supercargo/56844009ccf890a1f0763e2589ab89bd to your computer and use it in GitHub Desktop.
Set Task.Type on Enhanced Email Activities
trigger EmailTaskDefaultType on EmailMessage (after insert, after update) {
static final String EMAIL_TASK_TYPE_DEFAULT = 'Email';
List<Task> toUpdate = new List<Task>();
for (EmailMessage newEmailMessage : Trigger.new) {
if (newEmailMessage.ActivityId != null) {
EmailMessage oldEmailMessage = null;
if (Trigger.isUpdate) {
oldEmailMessage = Trigger.oldMap.get(newEmailMessage.Id);
}
if (oldEmailMessage == null || oldEmailMessage.ActivityId == null) {
Task t = new Task(Id=newEmailMessage.ActivityId);
t.Type = EMAIL_TASK_TYPE_DEFAULT;
toUpdate.add(t);
}
}
}
update toUpdate;
}
<?xml version="1.0" encoding="UTF-8"?>
<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>47.0</apiVersion>
<status>Active</status>
</ApexTrigger>
@IsTest
private class EmailTaskDefaultTypeTriggerTest {
@IsTest
static void thatRelationsAddedAfterInsertAreIncluded() {
Lead l = new Lead(FirstName='Test', LastName='Lead', Company='ACME Testing', Email='[email protected]');
insert l;
EmailMessage createdWithoutActivity = new EmailMessage(Subject='test subject', TextBody='test body', Status='3');
insert createdWithoutActivity;
EmailMessageRelation rel = new EmailMessageRelation();
rel.EmailMessageId = createdWithoutActivity.Id;
rel.RelationId = l.Id; // user id of the sender
rel.RelationType = 'ToAddress';
insert rel;
Test.startTest();
EmailMessage afterInsert = [SELECT Id, ActivityId FROM EmailMessage WHERE Id = :createdWithoutActivity.Id];
Id taskId = afterInsert.ActivityId;
Task t = [SELECT Id, Type, TaskSubtype FROM Task WHERE Id = :taskId];
System.assertEquals('Email', t.Type);
System.assertEquals('Email', t.TaskSubtype);
Test.stopTest();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment