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
mail.setSaveAsActivity(false);
mailList.add(mail);
Messaging.sendEmail(mailList);
It is throwing above exception when I pass userId inside setTargetObjectId.
mail.setTargetObjectId('005J00000076xlj');
It is working fine when I pass contactId or leadId.
Please help me to send email to UserId
Best Answer
setWhatId
is only available when insetTargetObjectId
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 thesetTreatTargetObjectAsRecipient(false)
to false. So your contact won't receive the email.