Email Template Send Email Example 2

 Trigger leadAssignment on Lead (after insert, after update) {

    if(Trigger.isUpdate){

        if(Trigger.isAfter){

            Set<Id> LeadsOwnerIds = New Set <Id>();

            for (Lead leadRec : Trigger.new) {

                if (leadRec.OwnerId != Trigger.oldMap.get(leadRec.Id).OwnerId) {

                    LeadsOwnerIds.add(leadRec.OwnerId);

                }

                system.debug('LeadsOwnerIds '+LeadsOwnerIds);

            }

            List <string> emailLst = New List <String> ();

            List <User> UserLst = [Select Id,Name,Email from user where Id In : LeadsOwnerIds];

            for(User usr : UserLst){

                emailLst.add(usr.Email);

            }

            system.debug('emailLst '+emailLst);

            EmailTemplate templateId = [select Id, Name FROM EmailTemplate where Name ='Lead Assignment Template'];

            // Create a l(ist of emails to send notifications to

            List<Messaging.SingleEmailMessage> mails =  new List<Messaging.SingleEmailMessage>();

                Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();

                //String[] toAddresses = new String[] {'loyobe5370@v3dev.com'};

            emailLst.add('loyobe5370@v3dev.com');  

            system.debug('emailLst22 '+emailLst);

            message.setToAddresses(emailLst);

            message.setTargetObjectId(UserLst[0].Id);

                message.setTemplateID(templateId.Id);//This is the template you are setting

                message.saveAsActivity = false;

                // Add the message to the list

                mails.add(message);

            

            // Send the emails

          // Messaging.sendEmail(mails);

            

            Messaging.SendEmailResult[] results = Messaging.sendEmail( new List<Messaging.SingleEmailMessage> {message} );

System.debug('Mail Sent'+results);

           

        }

    }

}

Comments

Popular posts from this blog

Custom List View Button In Salesforce

Get Record Id RecordId in LWC

PDF LWC (Link for pdf liabrary)