ActivityId on EmailMessage Object in Salesforce

ActivityId on EmailMessage Object in Salesforce

We will get INSUFFICIENT_ACCESS_OR_READONLY when we set ActivityId on the EmailMessage record with RelatedToId other than Case Record.

Sample Code:

objEmailMessage.RelatedToId = '0018c000026ZmPmAAK';//Hard Coded Account Id
objEmailMessage.ActivityId = '00T8c00003vrOJ5EAM';//Not supported

So, in order to have ActivityId on the EmailMessage, pass RelatedToId. The following sample code will auto-generate ActivityId since it creates Task record when the EmailMessage record is created.

Sample Code:

EmailMessage objEmailMessage = new EmailMessage(); 
objEmailMessage.status = '3';
objEmailMessage.fromName = 'Test Name'; 
objEmailMessage.subject = 'This is the Subject!'; 
objEmailMessage.htmlBody = '<html><body><b>Hello</b></body></html>'; 
objEmailMessage.toAddress = '[email protected], [email protected]';
objEmailMessage.CreatedDate = System.now().addDays( -365 );
objEmailMessage.RelatedToId = '0018c000026ZmPmAAK';//Hard Coded Account Id
List < Database.SaveResult > results = Database.insert( 
    new List< EmailMessage > { objEmailMessage }, false 
);

for ( Database.SaveResult sr : results ) {

    if ( sr.isSuccess() ) {
    
        System.debug( 'Email Message Created Successfully' );
        
    } else {
    
        for(Database.Error err : sr.getErrors()) {
        
            System.debug( 'Error code: ' + err.getStatusCode() );
            System.debug( 'Error message: ' +   err.getMessage() );
                        
        }
        
    }  
         
}

ActivityId can be set for EmailMessage record if the RelatedToId is Case. ActivityId can only be specified for emails on cases. It’s auto-created for other entities.

Reference Article:

https://developer.salesforce.com/docs/atlas.en-us.238.0.object_reference.meta/object_reference/sforce_api_objects_objEmailMessage.htm

Sample Code:

EmailMessage objEmailMessage = new EmailMessage(); 
objEmailMessage.status = '3';
objEmailMessage.fromName = 'Test Name'; 
objEmailMessage.subject = 'This is the Subject!'; 
objEmailMessage.htmlBody = '<html><body><b>Hello</b></body></html>'; 
objEmailMessage.toAddress = '[email protected], [email protected]';
objEmailMessage.CreatedDate = System.now().addDays( -365 );
objEmailMessage.RelatedToId = '5008c00001MB6TTAA1';//Hard Coded Case Id
objEmailMessage.ActivityId = '00T8c00003vrOJ5EAM';//Hard Coded Task Id
List < Database.SaveResult > results = Database.insert( 
    new List< EmailMessage > { objEmailMessage }, false 
);

for ( Database.SaveResult sr : results ) {

    if ( sr.isSuccess() ) {
    
        System.debug( 'Email Message Created Successfully' );
        
    } else {
    
        for(Database.Error err : sr.getErrors()) {
        
            System.debug( 'Error code: ' + err.getStatusCode() );
            System.debug( 'Error message: ' +   err.getMessage() );
                        
        }
        
    }  
         
}

Leave a Reply