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
Luffy Carl_opLuffy Carl_op 

Known the list of address, How to send Email with apex,using email template?

//EmailAddress is known, the  List of  address i want to send email.

String dn =  'My_Template_Name';
        
        Id tid;
        tid = [select id from EmailTemplate where developername =:dn ][0].id;   
           
        for(String saddr : EmailAddress ){
           
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            string [] toaddress= New string[]{saddr};
            email.setTemplateId(tid);
            email.setSubject('Attendance_System_Exception_Records_Alert');
            email.setPlainTextBody('Testing Apex Scheduler-Body');
            email.setToAddresses(toaddress);
            Messaging.sendEmail(New Messaging.SingleEmailMessage[]{email});
        }
Is there some problem with my code?
the schedule job give me a ERROR:

System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing targetObjectId with template: []

If you can help me , please.
 
CyberJusCyberJus
If you are using a template you have to specify the Contact, Lead, or User to send the message to. This makes sure the template merges the correct fields in. You are not able to use the setToAddresses with a template, so the targetObjectId is how you set who the email goes to. 

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_email_outbound_single.htm
Keyur  ModiKeyur Modi

i think you need to pass TargetobjectId from where you are fetching value and using it in emailTemplate .. like if you are retriving Email id From contact then you need to pass contactId as TargetSobjectId.