Share Your Experience With Others

What Happens When You Pass User’s Id in Single Email Message

Sometimes we need to send emails to internal users for example Opportunity Team Members or Account Team Members.

If we are using apex class to send emails using SingleEmailMessage class so there could be two kinds of code that we can use:

In this example, we are passing the user’s ids in setTargetObjectId and record id in setWhatId method to show merge fields values but we will get an error because setWhatId method can be used if we pass a contact id in the setTargetObjectId method otherwise you will get an email without merge values. This happens when you are using HTML Template.

Note: Either you will get email without merge field values or you will get an error in debug log as: Recipient missing for whatId

Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
mail.setOrgWideEmailAddressId(strOrgWideEmailId);
mail.setSaveAsActivity(false);
mail.setTreatTargetObjectAsRecipient(false);
mail.setTargetObjectId(userId);mail.setWhatId(oppid);//if we used this method then we will get err because it needs to pass the contact id not userid otherwise we will get email but without merge values
mail.setTemplateId(strTemplateId2);// if we are using html template

listEmails.add(mail);

To overcome this issue we can use another piece of code:

Messaging.SingleEmailMessage mail=Messaging.renderStoredEmailTemplate(strTemplateId2,null,oppid);
mail.setOrgWideEmailAddressId(strOrgWideEmailId);
mail.setSaveAsActivity(false);
mail.setTreatTargetObjectAsRecipient(true);
mail.setTargetObjectId(userId);
listEmails.add(mail);

But here the issue is, the method renderStoredEmailTemplate() counts against the SOQL limit so if you are creating one single email message variable for a single user it could hit your SOQL limit so what’s the solution?

The solution is you can use the first example code but you need to convert your HTML template to Visualforce template then pass your template id in the setTemplateId method, you will get an email without using the renderStoredEmailTemplate() method and with merge field values. Using the setTargetObjectId method will not count against email limit if you are passing salesforce internal user’s ids.

If anyone found something to be correct or has any other idea regarding this post please share in the comments.

Leave a comment