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
sfdc2002sfdc2002 

How to insert Activity History record after sending an email

Hi,
I cannot create a new Activity History record when using message.setSaveAsActivity(true);
 
This is my code:
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String AccId = apexpages.currentpage().getparameters().get('AccId');
            mail.setUseSignature(false);
            mail.setToAddresses(emaillist);
            mail.setSubject(' Details'); 
   	    mail.setSaveAsActivity(true);
            mail.setTargetObjectId(AccId);
            mail.setBccSender(true); 
            mail.setHtmlBody(templateBody);
            System.debug('===t===='+successmsg);
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Email send successfully'));

Thanks,
Chiyan SFDC
Maharajan CMaharajan C
Hi Chiyan,


setSaveAsActivity : It applies only if the recipient list is based on targetObjectId or targetObjectIds.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_base.htm?search_text=setTargetObject#apex_Messaging_Email_methods

As per document you are setting the setTargetObjectId and it value Should be LeadId or ContactId but you are setting the value as Account Id. If you are using the Acc Id here you will get the exception. So set some dummy contactId or LeadId which have the Email Address in setTargetObjectId

setTargetObjectId : 
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_single.htm?search_text=setTargetObject

Thanks,
Maharajan.C