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

Help with sending template email with Merge fields from custom object

I'm not understanding how merge fields work when using templates sent via apex.  Here is my current code:
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            Id templateId;
            String[] toAddresses = new String[]{''};
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});

What I'm still really confused about, even after reading the documentation, is what the setTargetObjectId and setWhatId actually do.  

I need to merge several fields from our custom project object, so I was assuming that's what I would use the specific project record id as the setTargetObjectId, but I'm not sure if that's correct as everything I've read says the setTargetObjectId is who you're sending the email to, which in this case is our sales admin.  
So, where / how do I set what the record is that I want to merge fields from, e.g. a specific project record.  Thanks in advance.
Rohit Sharma 66Rohit Sharma 66
setTargetObjectId is used to set the used whom we are sending out the email. For Object related merge fields you need to set in the setWhatId, where we will pass the Id of the custom object. Just give it a try and u will know how it will works.
I tried that but I'm getting an error now:
Apex trigger ProjectUpdateAfter caused an unexpected exception, contact your administrator: ProjectUpdateAfter: execution of AfterInsert caused by: System.EmailException: SendEmail failed. First exception on row 0; first error: INVALID_ID_FIELD, WhatId is not available for sending emails to UserIds.: [whatId, a001100000DKFu1]: Trigger.ProjectUpdateAfter: line 26, column 1

Any ideas?
Franciszek GrobelnyFranciszek Grobelny
Try with Messaging.renderStoredEmailTemplate(templateId, whoId, whatId);