6

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); – Boris Bachovski Apr 16 '15 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 Apr 16 '15 at 23:37
  • what if you remove any setCcAddresses or setBccAddresses ? – Cloud Ninja Apr 17 '15 at 1:42
  • Also did you try with a VF email template with the recipient as a User ? – Cloud Ninja Apr 17 '15 at 1:47
3

When I was faced with this, I

  1. Had a fixed Contact record with firstname = null, lastname = ErrorNotificationsDoNotDelete, email = errornotifications@mycompany.com 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.
| improve this answer | |
0

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);
m.setSaveAsActivity(false);
| improve this answer | |
  • 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 – Mitesh Sura Oct 29 '18 at 19:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.