Apex Trigger to Send a Custom Visualforce Component Email Template when Record is Created on Custom Object in Salesforce | How to send email template through apex trigger

2,149 views

Hey guys, today in this post we are going to learn about Apex Trigger to Send a Custom Visualforce Component Email Template when Record is Created on Custom Object in Salesforce.

Real time scenarios:- Write a trigger on Custom object (Registration__c) and Send a Custom Visualforce Component Email Template when Record is Created Condition is the Student Name should not be null.

Files we used in this post example

sendCustmTemp.apxt Apex Class Trigger It will be fire whenever a Record is Created Where Student name should not be null.
recipientsController.apxc Apex Class Controller Create Apex controller to send email template through Apex Class Method
emailNotifyTemp Create Classic Email Templates Create Classic Custom Email Templates.
regEmailTempVfc.vfc Visualforce Component Create Visualforce Component.
regTempController.apxc Apex Class Controller It is call on Visualforce Component.

Final Output

Why Should You Schedule Meeting?

🎯 If You Are Facing Any Of These 6 Challenges. Schedule Meeting With Me.

  • Learn Salesforce Development
  • Career Confusion
  • No Interview Call
  • Low Salary
  • No Promotion/Growth
  • No Finding New Job Opportunity
  • Why you stucking from past so many years in same company?

 

Apex Trigger to Send Email Template -- w3web.net

 

You can download file directly from github by Click Here.

 

Other related post that would you like to learn in Salesforce

Create Apex Class Trigger

Step 1:- Create Apex Class Trigger : sendCustmTemp.apxt

From Developer Console >> File >> New >> Apex Class

sendCustmTemp.apxt [Apex Class Controller]

  1.   TRIGGER sendCustmTemp ON Registration__c (BEFORE INSERT, BEFORE UPDATE, after INSERT, after UPDATE) {
  2.  
  3.   IF(TRIGGER.isAfter && (TRIGGER.isInsert)){
  4.     FOR(Registration__c myEmail:TRIGGER.new){
  5.  
  6.      Registration__c stuReg = [SELECT id,Name, RegNewStudent__r.Name FROM Registration__c WHERE id=:myEmail.id];
  7.              system.debug('myEmai444'+ stuReg.RegNewStudent__r.Name);
  8.  
  9.        IF(stuReg.RegNewStudent__r.Name != NULL){
  10.            recipientsController.sendEmail(stuReg.id);
  11.        }
  12.     }
  13.   }
  14.  
  15.  
  16. }

Create Apex Class controller

Step 2:- Create Apex Class : recipientsController.apxc

From Developer Console >> File >> New >> Apex Class

recipientsController.apxc [Apex Class Controller]

  1.   public class recipientsController {
  2.  
  3.     @AuraEnabled
  4.     public static void sendEmail(Id RegId){   //String toAddress, String Subject, String notes, String recId
  5.       	Registration__c newRegistration = NEW Registration__c();
  6.         newRegistration = [SELECT Id, Name, RegNewStudent__r.Name, RegCourse__r.Name, DateOfRegistration__c,sendSubjectLine__c, SendTemplateNote__c FROM Registration__c WHERE Id=: RegId];   
  7.         DOUBLE UNIQUE= math.random()* 10000 ;
  8.         String uniquestr = UNIQUE.format().remove(',').substring(0,4) ;
  9.         string mil =  UserInfo.getUserEmail();
  10.         string nm = 'test lastname' + uniquestr;
  11.         Contact tempContact = NEW Contact(email = mil, firstName = 'test' +uniquestr, lastName = nm);
  12.         INSERT tempContact;
  13.  
  14.  
  15.         //Fetching Email template
  16.         EmailTemplate templateId = [SELECT id FROM EmailTemplate WHERE Name LIKE 'emailNotifyTemp%' LIMIT 1];
  17.         system.debug('templateId:: '+templateId);
  18.        // string param1 ='<html>abcd</html>';       
  19.  
  20.         List<string> emailstr = NEW List<String>();
  21.         //lstIdTO.add(UserInfo.getUserEmail());
  22.         //emailstr.add('w3webmart@gmail.com');
  23.         emailstr.add('w3webnet@gmail.com');
  24.         list<Messaging.SingleEmailMessage> mail = NEW list<Messaging.SingleEmailMessage>();
  25.  
  26.         Messaging.SingleEmailMessage mails = NEW Messaging.SingleEmailMessage();
  27.         mails.setTemplateID(templateId.Id);
  28.         mails.setToaddresses(emailstr);
  29.         mails.setTargetObjectId(tempContact.id);
  30.  
  31.         system.debug('Mails'+mails); 
  32.         mail.add(mails);
  33.         //system.debug('mail#105 >>'+mail);
  34.         Messaging.sendEmail(mail); 
  35.         //system.debug('Ten Value >>'+mail);
  36.         //DELETE tempContact;
  37.  
  38.     }
  39.  
  40. }

Create Classic Email Templates

Step 3:- Create Classic Email Templates : emailNotifyTemp

File >> New >> Classic Email Templates >> emailNotifyTemp

emailNotifyTemp [Classic Email Templates File]

  1.   <messaging:emailTemplate subject="Registration Notification" recipientType="User" relatedToType="Registration__c">
  2. <messaging:htmlEmailBody >
  3.  
  4.     <p>w3web.net is the place where you can learn step-by-step about Blog, WordPress, Salesforce Lightning Component, Lightning Web Component (LWC), Visualforce, Technical of Computer Application, Salesforce Plugin, JavaScript, Jquery, CSS, Computer and Accessories, Software Configuration, Customization, Development and much more…</p><br/><br/>
  5.  
  6.    <c:regEmailTempVfc />
  7.  
  8. </messaging:htmlEmailBody>
  9. </messaging:emailTemplate>

Create Visualforce Component

Step 4:- Create Visualforce Component : regEmailTempVfc.vfc

File >> New >> Visualforce Component >> regEmailTempVfc.vfc

regEmailTempVfc.vfc [Lightning Component File]

  1.   <apex:component controller="regTempController" access="global">    
  2.  
  3.     <table border="1" cellpadding="5" cellspacing="5" style="border-collapse:collapse;">
  4.        <thead> 
  5.           <tr>
  6.               <td colspan="3"><span style="display:none;">Custom Label Img:-</span> <img src="{!$Label.w3webLabel}"  alt=""  align="left" width="134" height="60"/></td>
  7.               <td colspan="3"><span style="display:none;">Documet Img:-</span> <img src="https://vijay3327-dev-ed--c.ap4.content.force.com/servlet/servlet.ImageServer?id=0156F00000IvXxw&oid=00D6F000000GGe0&lastMod=1572421120000" width="50" height="40"/></td> 
  8.  
  9.           </tr> 
  10.          <tr style="background:rgb(0, 112, 210); color:#fff;">
  11.              <th>Reg No.</th>
  12.              <th>Student Name</th>
  13.              <th>Course Name</th>
  14.              <th>Date Of Registration</th>
  15.              <th>Subject Line</th>
  16.              <th>Template Note</th>
  17.          </tr>
  18.         </thead>
  19.        <tbody> 
  20.            <apex:repeat value="{!RegList}" var="regVar">
  21.                <tr>
  22.                    <td>{!regVar.Name}</td>
  23.                    <td>{!regVar.RegNewStudent__r.Name}</td>
  24.                    <td>{!regVar.RegCourse__r.Name}</td>                   
  25.                    <td>
  26.                        <apex:outputText value="{0,date,MM/dd/yyyy}">
  27.                             <apex:param value="{!regVar.DateOfRegistration__c}" /> 
  28.                        </apex:outputText>
  29.  
  30.                    </td>
  31.                    <td>{!regVar.sendSubjectLine__c}</td>
  32.                    <td>{!regVar.SendTemplateNote__c}</td>
  33.                </tr>
  34.            </apex:repeat>
  35.         </tbody>   
  36.     </table>
  37. </apex:component>

Create Visualforce Component Apex Class Controller

Step 5:- Create Apex Class : regTempController.apxc

From Developer Console >> File >> New >> Apex Class

regTempController.apxc [Apex Class Controller]

  1.   public class regTempController {
  2.  
  3.     public static List<Registration__c> getRegList(){
  4.         List<Registration__c> newRegistration;
  5.           newRegistration = [SELECT Id, Name, RegNewStudent__r.Name, RegCourse__r.Name, DateOfRegistration__c,sendSubjectLine__c, SendTemplateNote__c FROM Registration__c ];   
  6.  
  7.           RETURN newRegistration;
  8.     }
  9.  
  10. }

trigger to send email when record is created -- w3web.net

Further post that would you like to learn in Salesforce

 

 

FAQ (Frequently Asked Questions)

What is Apex class in Salesforce?

An Apex class is a template or blueprint from which Apex objects are created. Classes consist of other classes, user-defined methods, variables, exception types, and static initialization code.

What do Apex classes do?

An apex class is a blueprint or template from which objects are created. An object is the instance of a class. Apex class detail page. In apex, you can define an outer class also called top-level class, and you can also define classes within an outer class called inner classes.

What language is Apex based on?

Apex is based on familiar Java idioms, such as variable and expression syntax, block and conditional statement syntax, loop syntax, object, and array notation.

Related Topics | You May Also Like

 
  

Our Free Courses →

👉 Get Free Course →

📌 Salesforce Administrators

📌 Salesforce Lightning Flow Builder

📌 Salesforce Record Trigger Flow Builder

👉 Get Free Course →

📌 Aura Lightning Framework

📌 Lightning Web Component (LWC)

📌 Rest APIs Integration




Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net

Leave a Comment