Error: SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, WhatId is not available for sending emails to UserIds.

I want to send email through the snippet in below.

List < Messaging.SingleEmailMessage > mailList = new List < Messaging.SingleEmailMessage > ();
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTemplateId('00XJ0000000mq21MAA');//Email Template is
mail.setTargetObjectId('005J00000076xlj');//Contact,lead or userid to be specified.
mail.setWhatId('a03J000001Dc6vPIAR');//Custom object id

It is throwing above exception when I pass userId inside setTargetObjectId.


It is working fine when I pass contactId or leadId.

Please help me to send email to UserId


setWhatId is only available when in setTargetObjectId we specify Lead or contact Record ID.

So you are getting the expected behavior.

There is one workaround which I use. In setTargetObjectId give any dummy contact ID. SetToaddress method pass the UserId. And then set the setTreatTargetObjectAsRecipient(false) to false. So your contact won't receive the email.

  • no i still get the SendEmail failed. First exception on row 0; first error: INVALID_CROSS_REFERENCE_KEY, invalid cross reference id: [] – compski Dec 4 '19 at 14:35
  • @compskiI suggest you to create a new question and add details there. – Tushar Sharma Dec 4 '19 at 16:44
  • sure check this out salesforce.stackexchange.com/q/287192/38191 – compski Dec 4 '19 at 16:46

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.