+ Start a Discussion
Arvind SundararajanArvind Sundararajan 

How do I create an EmailMessage that shows up in Activity History?

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?
Patrick Souza 15Patrick Souza 15

Did you get any solutions?



Arvind, Patrick,

we could get this work and have both the email and the task created. However, the buttons that should allow to REPLY or FORWARD the email do not appear in the EmailMessage page. This would be the last step in allowing to receive and manage emails from within SalesForce. Are you trying to do anything similar?

David Tissen 7David Tissen 7
@SBgoo would be great if you could share your approach....
David Tissen 7David Tissen 7
The Answer is: Just Create the EmailMessage with relatedToId set to the sobject with the activity. No need to create the Task. 

@David Tissen and @SBgoo, Just like the original post in this thread is trying to map the Email Message to the contact, i am also trying to do the same. RelatedToId field on the EmailMessage cannot take in Contact , it can only take non-human entities like Account, Opps etc. So can you please explain how you did it with little more details? I saw this in other posts also, and this is not resolved there . Your inputs will be much appreciated.  This is the post i am referring to -> https://trailblazers.salesforce.com/answers?id=9063A000000DfsPQAS

Marek ZapletalMarek Zapletal
you can try the following solution with email message + email message relation:
my sample code:
// guide:
// sem is Messaging.SingleEmailMessage 
// owea is OrgWideEmailAddress

        EmailMessage em = new EmailMessage();
        em.EmailTemplateId = emailTemplate.Id;
        em.FromAddress = owea.Address;
        em.FromName = owea.DisplayName;
        em.HtmlBody = sem.getHtmlBody();
        em.Subject = sem.Subject;
        em.Incoming = false;
        em.Status = '3';
        em.TextBody = sem.getPlainTextBody();
        em.ToAddress = sem.getToAddresses()[0];
        em.ValidatedFromAddress = owea.Address;

        insert em;

        EmailMessageRelation emr = new EmailMessageRelation();
        emr.emailMessageId = em.Id;
        emr.relationId = contact.Id; //Lead Id, .....
        emr.relationType = 'ToAddress'; // OtherAddress, FromAddress,....
        insert emr;

Basavaiah RaviBasavaiah Ravi
Does it send email out to Contact or just create records only?