How to send email from server side (APEX Batch & Triggers) | Salesforce ☁️⚡️?

How to send email from server side (APEX Batch & Triggers)  | Salesforce ☁️⚡️?

Description

Hello Salesforce developers today I'll be explaining you all how we can send email from APEX. You may have encountered or will encounter the use case where you've to send the email when a certain task finished or begins.

Today I'll show you two methods to send email from apex.

  • Batch Apex Class
  • Apex Triggers

Batch Apex Class

What is Batch apex class? Batch Apex is an asynchronous execution of Apex code specially designed in a way so that it can process the large number of records and has greater flexibility in governor limits than the synchronous code.

Why we require Batch apex? Let's you have to use DML operations on more than 25,000 records in same transaction in this case salesforce will not allow to proceed with this due to the governor limits. As the limit is upto 10,000 if you want to bypass the limit we've to use batch apex.

Batch Apex implements Database.batchable interface. The interface has three methods named as Start(), Execute() and Finish() methods which should be implemented in the Batch Apex class which is supposed to implements this interface.

Start method: Start method is a point where you can collect your records to be processed by the execute method of the batch apex

Execute method: The actual processing point where your records take place in the execution.

Finish method: Finish method can have post job processing actions like sending an emails or call chain of another batch class if required.

global class BatchExample implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext BC) {
          //? This is starting of the batch job
        //? Here we'll collect records or object to be passes to next method
        return Database.getQueryLocator([SELECT Id, Name From Account WHERE Name LIKE '%test%']);
    }

    global void execute(Database.BatchableContext BC, List<Account> accList) {
        //? This is where all the logic takes place and everhing happenens
        for(Account acc : accList){
            acc.Name = acc.Name+' Batch';
        }
        try{
            UPDATE accList;
        }catch(Exception e){
            System.debug(e);
        }
    }   
   global void finish(Database.BatchableContext BC) {
        //? This is where we're doing all the post-processing operations'
        List<Messaging.SingleEmailMessage> mailLst = new List<Messaging.SingleEmailMessage>();
        Messaging.SingleEmailMessage mailObj = new Messaging.SingleEmailMessage();
        mailObj.setSenderDisplayName('Mail From Batch Class');
        mailObj.setBccSender(false);
        mailObj.toAddresses = new String [] {'Testingbatch@yopmail.com'};
        mailObj.setSubject('This is the mail form batch job');
        String body = 'Hello person, this is the sample template to send mail from batch apex job';
        mailObj.setHtmlBody(body);
        mailLst.add(mailObj);
        if(mailLst.size() > 0){
            Messaging.SendEmailResult[] res = Messaging.sendEmail(mailLst);
           if(res[0].success){
                System.debug('The mail was successfully send by batch apex job');
            }else{
                System.debug('The mail was a Failure');
            } 
        }
        }
    }

Apex Triggers

We all know when and how to use apex triggers, But in a nut shell. When we want to perform any action before and after changes to records. The actions like insertion, deletion, updation.

here's the example of sending email via trigger. We've taken a real life scenario which might help you to understand the whole concept a little thoroughly.

//* 3. Once an Account is inserted an email should go to the System Admin user with specified text below. 
    //*An account has been created and the name is “Account Name”.

public with sharing class Exercise03Mail {
    public static void Exercise03(List<Account> accLst){
        if(accLst.size()>0){
            List<Messaging.SingleEmailMessage> mailLst = new List<Messaging.SingleEmailMessage>();
            // Query to get the email from the profile name of system admin
            User usrObj = [SELECT Id,Email,Profile.Name FROM User WHERE Profile.Name='System Administrator'];
            for(Account acc : accLst){
                // check if the email of the user is not null
                if (usrObj.Email != null) {
                    Messaging.SingleEmailMessage mailObj = new Messaging.SingleEmailMessage();
                    mailObj.setSenderDisplayName('Salesforce Mail Trigger');
                    mailObj.setUseSignature(false);
                    mailObj.setBccSender(false);
                    mailObj.setSaveAsActivity(false);
                    mailObj.toAddresses = new String[] {usrObj.Email};
                    mailObj.setSubject('New Account was created');
                    String body = 'Dear System Administrator, <br/>';
                    body += 'An Account has been created and the name is '+acc.Name+'.';
                    mailObj.setHtmlBody(body);
                    mailLst.add(mailObj);
                }
            }
            if(mailLst.size() > 0){
                // Messaging.sendEmail(mailLst) " is used to send the list of mail
                Messaging.SendEmailResult[] res = Messaging.sendEmail(mailLst);
                if(res[0].success){
                    system.debug('The email was sent successfully');
                }else{
                    System.debug('The email was failed'+res[0].errors[0].message);
                }
            }
        }
    }
}

Did you find this article valuable?

Support Harshit Saxena by becoming a sponsor. Any amount is appreciated!