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
MPBSLMPBSL 

Email Template in Apex Class

Hi,

 

I wonder if we can we use email templates in apex class for sending emails?

 

Thanks.

Mayank

 

 

Force TechieForce Techie
Yes, You can!
crop1645crop1645

Here is a utility method I wrote that you can adapt

 

    //  -------------------------------------------------------------------------
    //  HELPER method: sendTemplatedEmail
    //  -------------------------------------------------------------------------
    public static void sendTemplatedEmail(String[] toRecipients, String[] ccRecipients, String templateApiName, ID targetObjId, Id whatId, ID orgWideEmailId, Boolean saveAsActivity, Attachment[] attachList ) {
      //  templateId   must be ID of an Email template
      //  targetObjId must be a Contact, User, Lead Id -- also used in merge fields of template recipient.xxxx
      //  whatId    must be an SObject that is used in the merge fields of the template relatedTo.xxxx
      //  fromId    if non null, use current user, otherwise, use this ID (most likely an org wide no reply id)
      //  bcc      not permitted when using templates
      
    Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        
    Id templateId;  
    try {templateId = [select id, name from EmailTemplate where developername = : templateApiName].id;}
    catch (Exception e) {
      throw new UtilException ('[U-03] Unable to locate EmailTemplate using name: ' + templateApiName + 
                    ' refer to Setup | Communications Templates ' + templateApiName);
    }
        
        
        email.setToAddresses(toRecipients);
        email.setCcAddresses(ccRecipients);
        email.setTargetObjectId(targetObjId);
        email.setWhatId(whatId);
        email.setorgWideEmailAddressId(orgWideEmailId);
        email.setTemplateId(templateId);
        email.setSaveAsActivity(saveAsActivity);      // save email as activity on the targetObjId (i.e. Contact). Note activity can't be saved on Users
        
        System.debug(LoggingLevel.INFO,'** entered sendTemplatedEmail, to:' + toRecipients + ' cc:' + ccRecipients +  ' templateId:' + templateId + ' tagetObjId:' + targetObjId + 
                        ' whatId:' + whatId + ' orgWideEmailId: ' + orgWideEmailId);
        try {
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
            return;
        }
        catch (EmailException e) {throw new UtilException('[U-02] sendTemplatedEmail error. ' + e.getMessage());}
      
    }  

 

johannjohann
That sample code is really helpful!  Thanks for sharing!!
arun sharma 37arun sharma 37
Thanks! I find it helpful. :) 
Deepali KulshresthaDeepali Kulshrestha
Hi, 

I have gone through your question. Yes, you can use the email template in the apex class to send email.

Please go through the code given below.

public class Handler_send_Email_on_LeadConvert {
    public static Boolean sendEmail(List<Lead> ldlist){
        try{
            Boolean sendSuccess  =  false;
            System.debug('lead List---->'+ldlist);
            Set<ID>   lID  =  new Set<ID>();
            if(ldlist != null){
                for(lead l : ldlist){
                    if(l.isConverted && l.Email != null){
                        lID.add(l.id);
                    }
                }
            }
            if(lid != null){
                List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
                EmailTemplate templateid  = [Select id from Emailtemplate where Name =: 'TestEmailTemplate' Limit 1];
                System.debug('Email Template Id ---->'+templateid);
                if(templateid != null){
                    for(ID i : lID){
                        Messaging.SingleEmailMessage  mail = new Messaging.SingleEmailMessage();
                        mail.setTemplateId(templateid.Id);
                        mail.setTargetObjectId(i);
                        mail.setSenderDisplayName(userInfo.getUserName());
                        mails.add(mail);
                    }
                    system.debug('mails--------------->'+mails);
                    for (Messaging.SendEmailResult r: Messaging.sendEmail(mails)){
                        if (r.isSuccess()){
                            sendSuccess = true;
                        }
                    }
                }
            }
            
            return sendSuccess;
        }
        catch(Exception e){
            System.debug('Line No:-->'+e.getLineNumber()+'----->Error---->'+e.getMessage()+'----->Cause----->'+e.getCause());
            return false;
        }
    }
}





I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com