I have a very simple error handling case. I need to send an email to the running user, who almost certainly does not have an associated Contact record. I also need to specify the error record in question so I can send a link to it. Easy, right?

However, according to the documentation for setWhatId:

If you specify a contact for the targetObjectId field, you can specify a whatId as well

So it doesn't work with a User Id. Why can't I send an email via template to a specific user about a specific record? This seems like a huge shortcoming in Apex. Creating a Contact record for each User is not an acceptable workaround.

  • Try specify the targetObjectId to be the user Id and in addition to that specify mail.setSaveAsActivity(false); Commented Apr 16, 2015 at 23:36
  • Yes I have also called setSaveAsActivity(false). I didn't think it relevant to the post, but I am already doing that.
    – Adrian Larson
    Commented Apr 16, 2015 at 23:37
  • what if you remove any setCcAddresses or setBccAddresses ?
    – brovasi
    Commented Apr 17, 2015 at 1:42
  • Also did you try with a VF email template with the recipient as a User ?
    – brovasi
    Commented Apr 17, 2015 at 1:47

2 Answers 2


When I was faced with this, I

  1. Had a fixed Contact record with firstname = null, lastname = ErrorNotificationsDoNotDelete, email = [email protected] under a known Account MyCompany *do not delete*
  2. Used the the running User's email as the 'to:' address in the Apex outbound email message
  3. Used the ID of the aforementioned Contact as the targetObjectId thereby enabling the whatId to be my object with the error details. The contact's Id was managed in a custom setting.

One work-around is to use Messaging.renderStoredEmailTemplate to create your Messaging.SingleEmailMessage. It allows a User for the targetObjectId and a whatId.

Messaging.SingleEmailMessage m = Messaging.renderStoredEmailTemplate(templateId, UserInfo.getUserId(), myWhatId);
  • This is great, but Salesforce email behavior is not consistent across UI and Apex. In apex we can use renderStoredEmailTemplate which does accept whoId as User/Contact/Lead. But when sending emails from the UI, it only supports Contact as p2_lkid parameter. It would be nice to have user/lead as recipient when sending emails from the UI too Commented Oct 29, 2018 at 19:50
  • Updates to above comment if is it not evident, I was referring to Classic Send Email screen which accepts ONLY Contactid as p2_lkid. We cannot pass LeadId or UserId. However, in Lightning the SendEmail popup supports all 3 and so does renderStoredEmailTemplate() in Apex Commented Apr 20 at 4:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .