Salesforce Apex: saveAsActivity

We have developed an Apex Trigger which will send an email notification to users whenever a task is edited. Instead of specifying the email address with the “setToAddresses()” function to the Messaging.SingleEmailMessage object, we use the “setTargetObjectId()” function. This can help to overcome the daily email governor limit that we have in Salesforce.

 

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

mail.setTargetObjectId(userId);
mail.setSubject(subject);
mail.setPlainTextBody(body);

 

However, during the testing, we hit into an error saying

System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_SAVE_AS_ACTIVITY_FLAG, saveAsActivity must be false when sending mail to users.
This only happens when we set the recipient by using the setTartgetObjectId() method. To solve this issue, we will just need to set the flag saveAsActivity = false to the Messaging.SingleEmailMessage object. For example:
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

mail.setTargetObjectId(userId);
mail.setSubject(subject);
mail.setPlainTextBody(body);
mail.saveAsActivity = false;


Hope this helps you all who have the similar issue.

Get in touch today to see how WDCi can help your business.