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
sridhar sridharsridhar sridhar 

Invalid Targetobject

Hi all, 
Greetings, 

I am facing a error while sending a email notification to the property (custom object Property__C) general manager. 
Error:
execution of AfterInsert caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_TYPE_FOR_OPERATION, Only User, Contact, Lead, or Person objects are allowed for targetObjectId:


Apex Code: 
=========
for (case cass : casss){

if(cass.Notify_Property__C == True ){
Csid=cass.Property_Name__c;
}
Property__c pr = [select id, General_Manager_Email__c from Property__C where id =: csid]; 

propertyId.add(pr.General_Manager_Email__c); 
string Emailaddress = pr.General_Manager_Email__c; 
if (propertyId.size()> 0){
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] address= new String[] {Emailaddress};
System.debug('Query email address ]]'+ address  );
mail.setToAddresses(address);
mail.setTargetObjectId(pr.id);

mail.setSenderDisplayName('Delivery notice');
EmailTemplate et=[Select id from EmailTemplate where Name=:'Product Delivery Notice'];
mail.setTemplateId(et.id);
Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

can you help on the issue. if any code changes need  you can twist and place it in the post. 

Thanks 
GulshanRajGulshanRaj
Hi Sridhar,

There are several approached to overcome TargetObjectID:
First approach) Create contact with the email id and delete just after Messaging.sendEmail(). 
Second approach) Follow this link (https://appirio.com/tech-blog/sending-emails-without-targetobject-id-apex) and see how we can sent email without using TargetObjectID.

Please let me know if you are struggling. 

Thanks & Regards
Gulshan Raj
LinkedIn (https://www.linkedin.com/in/gulshan-raj-a26b0640/)
Twitter (https://twitter.com/gulshan_bittoo)
Tushar khorgade 3Tushar khorgade 3
Hi Sridhar , I am Facing Same error When i try to send email from flow on Opportunity OBject, when stageName is Prospacting and email__c has some value i am getting Only User, Contact, Lead, or Person objects are allowed for targetObjectId: 0062w00000Lepg7. can u helpp me ou to resolve the issues.