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
Richard Clarke (Artisan)Richard Clarke (Artisan) 

Why would SendEmail not log to activity history in production but work in a sandbox?

The following code sends an email to a Contact using a template.
It works perfectly in a sandbox (email sent/received AND logged into activity history).
In our production work the email is sent/received but the activity history/task is not added.
I've tried coding the block a few ways as there are different ways of using SendEmail but in all cases I get the same outcome.
The code is running inside a future method.
If I run the code in anonyous apex it works as expected in production.
Any idea why an SendEmail call would not log activity history and not throw any exceptions?

Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.setTemplateId( emailTemplateId );
message.setSaveAsActivity( true ); 
message.setOrgWideEmailAddressId( XXXXXXId );
message.setTargetObjectId( contacts[0].Id );
message.toAddresses = new String[] { contacts[0].Id };
Messaging.SingleEmailMessage[] messages = new List<Messaging.SingleEmailMessage> {message};
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);
 
Wilfredo Morillo 20Wilfredo Morillo 20
After Winter 18, I was having a similar issue sending an email in a future method after creating an customer user. Test in sandbox and for some reason now I can send the email after the user insert. Check if your future job is in the queue in production, in my case was queue but taking a long  time to execute. 
Select id, JobType,methodName,Status from AsyncApexJob;

https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_asyncapexjob.htm