function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sandeep YadavSandeep Yadav 

INVALID_TYPE_FOR_OPERATION, Only User, Contact, Lead, or Person objects are allowed for targetObjectId:

Want to access custom object field values in email template.
Here is what i did-
 
public static void sendCreationEmail(Service_Request__c srNew){
        string ldOwnerMail = srNew.Owner.Email;
        Messaging.SendEmailResult[] results;
        if(ldOwnerMail != null && ldOwnerMail != ''){
            Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
            message.setToAddresses(new String[] {ldOwnerMail});
            message.setTemplateId([select id from EmailTemplate where DeveloperName='Service_Request_Creation'].id);
            message.setSaveAsActivity(false);
            message.setWhatId(srNew.Id);
            message.setTreatTargetObjectAsRecipient(false);
            message.setTargetObjectId('01I6g000000shKzEAI');// Id of custom Object.
            
            results = Messaging.sendEmail(new Messaging.SingleEmailMessage[]{message});
        }
    }

Any Help on this ?
Foram Rana RForam Rana R
Hi Sandeep,

I hope you are doing well .....!!
Please use the below Image:
User-added image
I have gone through your code In setTargetObjectId, you have specified custom object that's why you got this error.
If you are using merge field then write setTargetObjectId otherwise it's optional.

Hope this helps you.
If this helps kindly mark it as solved so that it may help others in the future.

Thanks & Regards,
Foram Rana
Sai Sri GanapathineediSai Sri Ganapathineedi
Similar discussion:

https://salesforce.stackexchange.com/questions/304894/invalid-type-for-operation-only-user-contact-lead-or-person-objects-are-allo