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

1 Answer 1


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, 2019 at 14:35
  • @compskiI suggest you to create a new question and add details there. Dec 4, 2019 at 16:44
  • sure check this out salesforce.stackexchange.com/q/287192/38191
    – compski
    Dec 4, 2019 at 16:46

You must log in to answer this question.

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