[SalesForce] setsaveasActivity

I am trying to send an email to Order Contact and Order Owner and saving it as Completed Task(Activity History) against Order but Sent Email is saved against Contact's Activity History.How to save it against Order ?

    for(Order o:oList){
        Messaging.SingleEmailMessage OrderContactMail = new Messaging.SingleEmailMessage();
        OrderContactMail.setCcAddresses(new List<String>{o.Owner.Email}); 
        OrderContactMail.SaveAsActivity(true);
        String messageBody = 'some sample message';
               OrderContactMail.setSubject(subject);
               OrderContactMail.setHtmlBody(messageBody);
               OrderContactMail.setSaveAsActivity(true);
               OrderContactMail.setTargetObjectId(o.Contact__c);
               mails.add(OrderContactMail);
       }
     Messaging.sendEmail(mails);

From Docs :

setSaveAsActivity(Boolean)

Optional. The default value is true, meaning the email is saved as an
activity. This argument only applies if the recipient list is based on
targetObjectId or targetObjectIds. If HTML email tracking is enabled
for the organization, you will be able to track open rates.

setTargetObjectId(ID)

Required if using a template, optional otherwise. The ID of the
contact, lead, or user to which the email will be sent. The ID you
specify sets the context and ensures that merge fields in the template
contain the correct data.

Best Answer

You need to supply "what id" as well.

OrderContactMail.setWhatId(o.id);

Related Topic