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
Staci CaraStaci Cara 

renderStoredEmailTemplate()

I urgently need help with a emailing issue. I want to send an E-mail once some fields in user get changed and everything works fine except that when I want to send the Email to 200 people I am getting the error that I am hitting the limits because it is within a loop. I tried to solve it with an extra class that has all the Message and SingeEmailMessage methods that I need and that implements Queueable. Like that I created a queue that is taking all users that shall get the email. But now I am getting the error: System.LimitException: Too many queueable jobs added to the queue: 51
What I had so far without the extra class:

List<Messaging.SingleEmailMessage > msgList = new List<Messaging.SingleEmailMessage>(); 
        EmailTemplate template = [select Id from EmailTemplate where DeveloperName = : 'My_template']; 
        Messaging.SingleEmailMessage emailMsg; 
        for (User u : [SELECT Id, user_field__c FROM User WHERE Id IN: trigger.new]){ 
             if(u.user_field__c != null){ 
                emailMsg = Messaging.renderStoredEmailTemplate(template.id, u.id, null); // Here appears the error caused by the looping of users
                emailMsg.setSaveAsActivity(false);
                emailMsg.setTreatTargetObjectAsRecipient(false); 
                String[] recipients = new String[]{test@hotmail.com};
                emailMsg.setToAddresses(recipients); 
              } msgList.add(mail); 
        } Messaging.sendEmail(msgList);

Like I said, the alternativ way is to put everything in an separate class that implements Queueable and then call the queue after the IF, like this: System.enqueueJob(new SendingEmail(userLst, template.id, null, false, false)); 

I would prefer to have everything in one class, but how can I avoid hitting the gov.limits when calling Message.renderStoredEmailTemplate(). Any ideas how I can make this solution work? 
Thank you in advance!

Eduardo Offermann PalmaEduardo Offermann Palma
Hi Staci, Perhaps my answer it's a "little" late but I hope helps.

Apparently maybe you have to use emailMsg.singleEmail.setTemplateId(template.Id) instead of renderStoredEmailTemplate. Have you tried that?