How to reference Email template using Apex

How to reference Email template using Apex

setTemplateId is used to use Email template using Apex.

Sample Code:

trigger MemberTrigger on Member__c (after insert)
{
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    List<String> ccAddresses = new List<String>();
    ccAddresses.add('[email protected]');
    for(Member__c mem:trigger.new)
    {      
        mail.setTemplateId('00XU0000000YOlG'); //Id of the Email Template
        mail.setCcAddresses(ccAddresses);
        mail.setTargetObjectId('005U0000000gpc1'); // Id of Contact or Lead or User
        mail.setSaveAsActivity(false);
        mail.setWhatId(mem.Id); //Optional field to ensure proper merging of objects in template
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

Leave a Reply