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

Call Email Alert (template) from Apex

Is there a way to call an existing Email alert and pass it a record value for the merge fields? The object generating the email alert is a custom object called Account_Counselor__c. This alert is sent to myself and another admin when a APEX CLASS attempts to add a UserPackageLicense but there are no licenses available from PackageLicense. This alert will let us know that we need to buy more licenses. I already have the email alert setup and it works fine from a Visual Flow but I can't figure out how to call it from APEX as well. 
Abhishek BansalAbhishek Bansal
Hi Matt,

You can use the below code to send Email throug Apex class:
List<EmailTemplate> lstEmailTemplates = [SELECT Id, Body, Subject from EmailTemplate where DeveloperName = 'Your Email Template Unique Name'];

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId(contactId);// Any contact or User id of your record
mail.setToAddresses(new list<string>{'',''});

mail.setWhatId(; // Enter your record Id whose merge field you want to add in template
Messaging.SendEmailResult[] resultMail = Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

//Please replace "Your Email Template Unique Name" with your template name

Let me know if you have any issue or if you want any other help.

Brian Oconnell 23Brian Oconnell 23
That does not explain how to use an existing Email Alert from Apex.  Administrators may need to change recipients or templates without editing code.
Alekya AtluriAlekya Atluri
How can we use the existing email template,I just want to call the existing email template from apex trigger.Any solutions?