• Patrick Souza 15
  • NEWBIE
  • 0 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
I am implementing an EmailService. I would like to store the emails I receive as an EmailMessage that would show up on the ActvityHistory for a record like Contact or Account. To do that I wrote the following code (treat it as pseudo code) : 

Task emailTask = new Task (
            ActivityDate  = Date.today(),
            Description   = results.getEmailBodyAsText(),
            // IsArchived    = False, -- This is not writable
            IsRecurrence  = False,
            IsReminderSet = False,
            OwnerId       = results.getPrimaryUser().Id,
            Priority      = 'High',
            Status        = 'Open', // Revisit this - We should check if an email requires response
            Subject       =    results.getSubject(),
            TaskSubType   = 'Email',
            WhoId         =  results.getPrimaryContact().Id
        );


        insert emailTask; // This will provide an Id
        // Notes: Salesforce Requires a Task be Present to associate
        // with it an EmailMessage. Email Message provides a cleaner
        // looking inteface for Emails
        EmailMessage emailMessage = new EmailMessage(
            ActivityId  = emailTask.Id,
            FromAddress = ((Contact)results.getSender()).Email,
            FromName    = ((Contact)results.getSender()).Name,
            Incoming    = False,
            MessageDate = Date.today(),
            Subject     = results.getSubject()
        );
        insert emailMessage;

Where "results" is an object that is created from parsing the Inbound Email (Some decoupling from that Object).  When I do this I get the following error - 
Line: 42, Column: 1
System.DmlException: Insert failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_OR_READONLY, You cannot edit this field: [ActivityId]

Based on the document on EmailMessage it appears that ActivityId is the Id of the task that the email replaces in the ActivityHistory. I would like to use the EmailMessage object because it looks much cleaner than a Task that is of an Email SubType. Any ideas how to get this to really work?