Send an Email using Apex Trigger?

on

|

views

and

comments

Table of Contents

Introduction to Apex Scenario

Develop an Apex Trigger to send the email to the Account owner when the Account is Created within Salesforce and Account does not have the phone and industry field populated.

Also, create a task under the account with the following information

  • Subject – The phone and Industry of the Account are Blank
  • Description – The phone and Industry of the Account are Blank
  • Priority – High
  • Status – Not Started
  • What Id – Related Account Id
  • OwnerId – Related Account Owner

Email Template

Dear <Account Owner>

A new account <account name> has been created in Salesforce. The account is missing some important information Phone & Industry.

Please try to collect this information and update the account ASAP.

Thanks & Regards,
<Company Name>

Questions to be asked

  • Which Object?
    • Account
  • Event?
    • after insert
  • Requirement?
    • Send an Email & Create a Task

Hands-On

Email Utility Class

				
					public class EmailUtility {

    public static void sendEmail(){
        // To Address
        // Body (Content)
        // Subject
        // CC Address
        // BCC Address
        // Attachments (Files)
        // Messaging
        /* Step1 - Create the object of SingleEmailMessage */
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setSubject('My First Email From Salesforce');
        // Images/Buttons/Links/Bold/Color - HTML Body
        // Simple Text - Plain Text Body
        //email.plaintextbody = '';
        //email.toaddresses = '';
        List<String> toAddress = new List<String>();
        toAddress.add('sfdcpanther@gmail.com');
        toAddress.add('sfdcpanther@gmail.co');
        
        List<String> bccAddress = new List<String>();
        bccAddress.add('contentlearning222@gmail.com');
        
        email.setPlainTextBody('Hello Dear, My First Email From Salesforce!');
        email.setToAddresses(toAddress);
        email.setBccAddresses(bccAddress);    
        
        List<Messaging.SingleEmailMessage> emailMessages = new List<Messaging.SingleEmailMessage>();
        emailMessages.add(email);
        List<Messaging.SendEmailResult> sendEmailResults = Messaging.sendEmail(emailMessages, false);
        for(Messaging.SendEmailResult sr: sendEmailResults){ // 10 Emails - 8 Success, 2 Fail
            Boolean isSuccess = sr.isSuccess(); // True OR False
            if(isSuccess){
                System.debug('Email Sent Successfully!!');
            }else{
                System.debug('Error while sending Email \n ');
                List<Messaging.SendEmailError> errors = sr.getErrors();
                System.debug(errors);
            }
        }
        //public Messaging.SendEmailResult[] sendEmail(Messaging.Email[] emails, Boolean allOrNothing)
    }
    
    /*public class Messaging{
        public class SingleEmailMessage{
            
        }
    }*/
}
				
			

Handler Class

				
					public class AccountTriggerHandler {
    // before insert
    public static void handleBeforeInsert(List<Account> accountList){
        AccountTriggerHelper.updateAccountShippingAddress(accountList); 
        AccountTriggerHelper.checkDuplicateAccount(accountList);
    }
    // before update
    public static void handleBeforeUpdate(List<Account> accountList){
        AccountTriggerHelper.updateAccountShippingAddress(accountList);
        AccountTriggerHelper.checkDuplicateAccount(accountList);
    }
    //After insert
    public static void handleAfterInsert(List<Account> accountList){
        /*
            When the Account is Created,
            Create a Task Record under that Account and assign the Task to the Account Owner.
            Use the below information
            * Subject - Created from Apex Trigger
            * Description - Created from Apex Trigger
            * Due Date - Todays Date + 7
            * Status - Not Started
            * Priority - High
            * OwnerId - Account OwnerId
            * WhatId - Account.Id
        */
        /* Sub-Problems */
        // 1. Check if the code is running after insert
        // Do not make any DML withing for loop ( LIMIT - 150 ~ 151 )
        // Do not make any SOQL withing for loop ( LIMIT - 100 ~ 101 )
        
        List<Task> taskRecordToInsertList = new List<Task>();
        List<Messaging.SingleEmailMessage> emailMessages = new List<Messaging.SingleEmailMessage>();
        
        List<Account> newAccountList = [SELECT Id, Name, Phone, Industry, OwnerId, Owner.Name, Owner.Email FROM Account WHERE Id IN: accountList];
        
          for(Account acc : newAccountList){ // Trigger.size = 200
            // Prepare Task Record
            if(acc.Phone == null && acc.Industry == null){ // 20
                
                // Requirement #1 - Create Task
                Task t = new Task();
                t.Subject = 'Created from Apex Trigger';  
                t.Description = 'Created from Apex Trigger';
                t.Status = 'Not Started';
                t.Priority = 'High';
                t.ActivityDate = System.today().addDays(7);
                t.WhatId = acc.Id;
                t.OwnerId = acc.OwnerId;
                taskRecordToInsertList.add(t);
                
                // Requirement #2 - Send Email
                // Prepare Email - DRAFT Email
                Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                email.setSubject('New Account '+acc.Name+' has been assigned!');
                // OwnerId (User/Queue)
                String emailBody = 'Dear '+acc.Owner.Name+' <br/><br/>';
                emailBody += 'A new account <b>'+acc.Name+'</b> has been created in Salesforce. The account is missing some important information Phone & Industry.<br/><br/>';
                emailBody += 'Please try to collect this information and update the account ASAP.<br/><br/>';
                emailBody += '<b>Thanks & Regards,<br/>';
                emailBody += 'Panther Schools</b>';
                
                //email.setPlainTextBody(emailBody);
                email.setHtmlBody(emailBody);
                
                List<String> toAddress = new List<String>();
                // Lead/Contact/User - Email/Id
                toAddress.add(acc.OwnerId); // OwnerEmail
                email.setToAddresses(toAddress);
                
                List<String> bccAddress = new List<String>();
                bccAddress.add('contentlearning222@gmail.com');
                
                email.setBccAddresses(bccAddress);
                
                // Prepare the Attachment and send along with the email
                Messaging.EmailFileAttachment attach = new Messaging.EmailFileAttachment();
                attach.setFileName('Panther-Schools.txt'); // pdf, txt, png, jpg, jpeg, word, zip
                
                String strBody = 'This is simple text attached from Salesforce';
                Blob textBody = Blob.valueOf(strBody);
                attach.setBody(textBody);
                
                List<Messaging.EmailFileAttachment> fileAttachments = new List<Messaging.EmailFileAttachment>();
                fileAttachments.add(attach);
                
                email.setFileAttachments( fileAttachments );
                
                email.setReplyTo('no-reply@gmail.com');
                email.setSenderDisplayName('Amit From Panther Schools');
                // Add Email to the List
                emailMessages.add(email);
            }
        }
        // insert Task Record
        insert taskRecordToInsertList;
        // 200 times
        
        // Send Email
        List<Messaging.SendEmailResult> sendEmailResults = Messaging.sendEmail(emailMessages, false);
        for(Messaging.SendEmailResult sr: sendEmailResults){ // 10 Emails - 8 Success, 2 Fail
            Boolean isSuccess = sr.isSuccess(); // True OR False
            if(isSuccess){
                System.debug('Email Sent Successfully!!');
            }else{
                System.debug('Error while sending Email \n ');
                List<Messaging.SendEmailError> errors = sr.getErrors();
                System.debug(errors);
            }
        }
    }
    // after the update
    public static void handleAfterUpdate(){
        
    }
    
    
}
				
			

Watch Complete Video

Resources

Amit Singh
Amit Singhhttps://www.pantherschools.com/
Amit Singh aka @sfdcpanther/pantherschools, a Salesforce Technical Architect, Consultant with over 8+ years of experience in Salesforce technology. 21x Certified. Blogger, Speaker, and Instructor. DevSecOps Champion
Share this
5 out of 5

Leave a review

Excellent

SUBSCRIBE-US

Book a 1:1 Call

Must-read

How to Utilize Salesforce CLI sf (v2)

The Salesforce CLI is not just a tool; it’s the cornerstone of development on the Salesforce Platform. It’s your go-to for building, testing, deploying, and more. As one of the most important development tools in our ecosystem

Save the day of a Developer with Apex Log Analyzer

Table of Contents What is Apex Log Analyzer? Apex Log Analyzer, a tool designed with Salesforce developers in mind, is here to simplify and accelerate your...

Salesforce PodCast

Introduction Hey Everyone, Welcome to my podcast, the first-ever podcast in India for Salesforce professionals. Achievement We are happy to announce that we have been selected as Top...

Recent articles

More like this

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Hi Amit, I am unable to find Trigger assignments, could you please share that assignment? Thank you for the valuable content.Send an Email using Apex Trigger?
5/5

Stuck in coding limbo?

Our courses unlock your tech potential