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
Ant BackhouseAnt Backhouse 

SingleEmailMessage not saving as Activity in class method in production. Does when executing Anonymous Apex in production. Any ideas? How to debug?

Hi All,

I wrote a class method for sending a single email message in my staging environment and the expected default behaviour of being saved as an activity worked. Moving to production, the saving as activity failed. Moreover, I can execute the code as anonymous apex and it saves as activity in the prod org. Here is the method:
 
public with sharing class EmailUpdateController {

	public static void sendTemplateEmail(String templateId, String whoId, String whatId) {
		Messaging.reserveSingleEmailCapacity(1);				
		Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
		email.setUseSignature(false);	
		email.setTemplateId(templateId);
		email.setTargetObjectId(whoId);
		email.setWhatId(whatId);
		List<Messaging.SendEmailResult> results = Messaging.sendEmail(new List<Messaging.SingleEmailMessage>{email});
		Boolean returnValue = true;
		for (Messaging.SendEmailResult er : results) {
			System.debug(er.isSuccess());
			if(!er.isSuccess()) {
				System.debug(er.getErrors());
				returnValue = false;
			}
		}
		System.debug('Success was '+returnValue);
		
	}

}

This method works fine in staging and also running this in the dev console in production works.

Running code in Developer Console

I get activity as expected
Activity on Opportunity
When running the method however, eg: 
EmailUpdateController.sendTemplateEmail('00X0I000001dmpUUAQ', '00328000015yPZXAA2', '0060I00000R9fIMQAZ');

No activity is saved.  

Appreciate your help. I've been pulling my hair out with this.
Ryan GreeneRyan Greene
Add this around line 7: 
email.setSaveAsActivity(true);
Ant BackhouseAnt Backhouse
Thanks for the reply. Unfortunately, this doesn't work. I added this just to be sure. Though I understand setSaveAsActivity(true) is the default behaviour for SingleEmailMessage and works both in staging and in executing anonymous apex without explicitly calling that method.