1

Context I have a JS button in the case layout that sends an email to the contact via Apex.

Problem How can I save that sent email to the case's Activity History?

I've found similar questions, like this one, but it wasn't replied, and I haven't been able to find any other useful information.

I've tried:

mail.setTargetObjectId(contactId);
mail.setWhatId(caseId);
mail.setSaveAsActivity(true);

but it just saves it to the contact, which is not what I need.

Thanks in advance!

1 Answer 1

3

Note that, Only User, Contact, Lead, or Person objects are allowed for targetObjectId and it is mandatory.

Ideally, if you want to send an email to Contact then put ContactId as targetObjectId

So, if you don't like to put Contact then use UserId as targetObjectId.

Moreover, if you have activity on Contact it will also be reflected under Account.

Following code save the email under ActivityHistory of Case, Contact and Account.

List<Messaging.SingleEmailMessage> messages = new List<Messaging.SingleEmailMessage>();
Messaging.SingleEmailMessage theMessage = new Messaging.SingleEmailMessage();

theMessage.setTemplateId(emailTemplateId);

theMessage.setTargetObjectId(this.myCase.ContactId);

List<String> toAddress = new List<String>();
toAddress.add(this.myCase.Contact.Email);
theMessage.setToAddresses(toAddress);
theMessage.setWhatId(this.myCase.Id); 
theMessage.setSaveAsActivity(true); 
messages.add(theMessage);    
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
4
  • I know, but my question is how can I save it under the case's ActivityHistory, not the contact's. Commented Jul 9, 2017 at 22:01
  • this will save under ActivityHistory of Case, Contact and Account Commented Jul 9, 2017 at 22:03
  • Oh, darn, the combination of the three! That was so stupid of me, I tried combining them, but never thought of using the three properties at the same time. True. Thanks a lot, Santanu! Commented Jul 9, 2017 at 22:12
  • OK but we often have Cases without any Contact. So the Contact Id is not available. Is there a way to save a record of the outgoing email on the Case (WhatId)?
    – Bryan
    Commented Jun 18, 2018 at 13:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .