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
David BinsteadDavid Binstead 

Finding Owner of Task from ActivityId in EmailMessage Object

Hello,

Trying to move attachments on outbound emails to the matching Task on Cases, however i'm getting the error "System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, Attachment owner must be the same as the owner of the parent task or event.: [OwnerId]"

My aim is to find the userId of the user who created the task, via ActivityID on the emailMessage object and use this when adding  a new attachment with the task as the owner.

The problem is that I can't find any reference to ActivityID when querying the task. Does anybody know how to related the ActivityID on the emailMessage object to the task. One would assume this would be the task Id but this does not seem to be the case?

Cheers

Code snipped- ------

Map<Id, EmailMessage> eMessage = new Map<Id, EmailMessage>([select id, ActivityId, ReplyToEmailMessageId, ParentId, (select Id from attachments) from EmailMessage where ParentId in:cIds]);
     
          
     
      for (EmailMessage a : eMessage.values()){
       system.debug (a.id);
       msgTest += a.id + ' ';
     
       if (a.attachments != null){
        for(attachment atc: a.attachments){
      attIds.add(atc.Id);
      system.debug ('attchment ID' + atc.Id);
     }
       }//if
      }//for


List<Attachment> attCopies = new List<Attachment>();

List<Attachment> Atts = [select Id, name, body, Parentid from Attachment where Id in:attIds];

for(attachment att: Atts)
{
  if (eMessage.get(att.parentID).ActivityId != null) {
       
   
   attachment copyAtt = new Attachment(name = att.Name, body = att.Body, ParentId = eMessage.get(att.parentID).ActivityId, ownerid = xxxxxx);
   system.debug ('this is the activity ID - attachment will be updated' + eMessage.get(att.parentID).ActivityId + ' for item email ID ' +  eMessage.get(att.parentID).ActivityId);
   
   attCopies.add(copyAtt);
   }   
}




lakslaks
Hi,

From the Attachment you can get the Case/Task it is related to, and from there you can get the User.

Check the info below:

EmailMessage (ActivityId -> corresponding Task )

Task (WhatId -> corresponding Case)
Case (OwnerId -> Corresponding User/Group)

Attachment (ParentId -> Case/Task)

Hope this helps.

Regards,
Lakshmi.
lakslaks
Hope you are aware of the workbench provided by Salesforce - https://workbench.developerforce.com/login.php

It is very useful in understanding the different Standard, Custom objects in your Org, their fields, relationships etc.
And for doing a whole lot of other things.

Do check it out.

Regards,
Lakshmi.