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
kailash chandra 25kailash chandra 25 

how can i send email through custom object?

I want to send email through custom object  

List<Messaging.SingleEmailMessage> allmsg = new List<Messaging.SingleEmailMessage>();
        EmailTemplate emailSickEmpTemplate = [Select Id from EmailTemplate where developername = 'Email_with_list_of_sick_employees'];
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setTemplateID(emailSickEmpTemplate.Id); 
        mail.setTargetObjectId(Userinfo.getUserId());
        mail.setSaveAsActivity(false);
        mail.setOrgWideEmailAddressId(owa.id);
        allmsg.add(mail);
        Messaging.sendEmail(allmsg,false);

This is the exception:

|SendEmail failed. First exception on row 0; first error: INVALID_TYPE_FOR_OPERATION, Only User, Contact, Lead, or Person objects are allowed for targetObjectId: a020v000002n3sr.: [targetObjectId, a020v000002n3srAAA]
Best Answer chosen by kailash chandra 25
SPURANSPURAN
Hi Kailash,

TargetObjectId parameter is used to set the recipient of the email. You cannot set that value to a Custom Object Id, If you are trying to send an email to a User selected on one of the lookups on the Custom Object Record, then query for the Id and assign that to TargetObjectId.

All Answers

SPURANSPURAN
Hi Kailash,

TargetObjectId parameter is used to set the recipient of the email. You cannot set that value to a Custom Object Id, If you are trying to send an email to a User selected on one of the lookups on the Custom Object Record, then query for the Id and assign that to TargetObjectId.
This was selected as the best answer
Raj VakatiRaj Vakati
Try this
 
List<Messaging.SingleEmailMessage> allmsg = new List<Messaging.SingleEmailMessage>();
        EmailTemplate emailSickEmpTemplate = [Select Id from EmailTemplate where developername = 'Email_with_list_of_sick_employees'];
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setTemplateID(emailSickEmpTemplate.Id); 
        mail.setTargetObjectId(emailSickEmpTemplate.OwnerId);
        mail.setSaveAsActivity(false);
        mail.setOrgWideEmailAddressId(owa.id);
        allmsg.add(mail);
        Messaging.sendEmail(allmsg,false);

 
kailash chandra 25kailash chandra 25
Hi,
I explored this topic in my own org, finally we cant send email through custom object Because salesforce doesn't allow mail.setTargetObjectId(custom_object_record_id) 
above solution will be send mail to owner of email template while i need to send email to the custom object.