function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Robert Davis 1Robert Davis 1 

Trigger on EmailMessage - Create Task

I would like to create a Completed Tasks for when an Email is sent from the Contact Page. The reason being is we capture particular values in custom fields when the email is sent based on the different profiles. I think my problem is that I am unable to capture the Contact ID which then means I am unable to capture the Account ID for the Task.
 
Trigger:

trigger Create_Task_Trigger on EmailMessage (after insert) {
    
    Create_Task_TriggerHandler.After_Insert(Trigger.new);

}

Trigger Handler:

public class Create_Task_TriggerHandler {
    
    public static void After_Insert(List<EmailMessage> EmailMessage){
        List<Task> tsk = new List<Task>();
        for(EmailMessage em: EmailMessage){
            System.debug('EmailMessage.RelatedtoID '+em.RelatedToId);
            for(Contact cont : [SELECT Accountid, id FROM Contact WHERE id=: em.RelatedToId]){
                Task tsk1 = new Task();
                tsk1.WhatId = cont.AccountId;
                system.debug('Account ID '+ cont.AccountID);
                tsk1.WhoId = cont.Id;
                system.debug('Contact ID '+cont.id);
                tsk1.Subject = 'EMAIL SENT : '+ em.Subject;
                tsk1.OwnerId = UserInfo.getUserId();
                tsk1.Sales_Activity__c = 'SENT EMAIL';
                tsk.add(tsk1);
             }
        }
        Insert tsk;
        
    }

}

It appears that the EmailMessage.RelatedToID is null. Any ideas on how I might solve this issue?

Your help is appreciated.

Robert