Send Birthday Email To Contacts – The Apex Way.

There are several ways to send the birthday email to the contacts in Salesforce.com. We shared the workflow way in the previous post. The workflow is a great no-code option, but it does not control the time the email to be sent out because there is no guarantee when the time-based workflow to be triggered. This post we guide you on how to send the birthday email to contacts using scheduled apex/batch. You can download the app from AppExchange https://appexchange.salesforce.com/appxListingDetail?listingId=a0N3A00000G12sQUAR&preview=%222020-05-19T13%3A08%3A50.000Z%22

  • To be able to send an email message, we will use Messaging.SingleEmailMessage class to send to recipients/who/what.
public class EmailService {
	//Send email class
    public static Messaging.SingleEmailMessage getEmailTemplate( String TempName,Id contactId){
        
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        Id tempID; // template ID
        Try{
            tempID = [select Id from EmailTemplate where developername =: TempName].id;
        }catch(Exception e){
            return null; // If there is no template existed return null as error
        }
        email.setTargetObjectId(contactId);
        email.setTemplateId(tempID);
        return email;                                                        
    }
}
  • Create an email email template to say happy birthday.
  • Create a batch job to query which contacts have a birthday today. Batch Job is a great feature of Salesforce which allow you to process numerous data set with millions of records.
global class SendBirthdayEmailBatch implements Database.Batchable<sObject>{   
    
    global SendBirthdayEmailBatch(){
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        //Get today by
        string query = '';
        Date tday = System.today();
        Integer day = tday.day(); //get day of month
        Integer month = tday.month(); // get month
        //Query Contact ID to use to send email template
        query = 'select id from Contact where CALENDAR_MONTH(Birthdate) = :month and DAY_IN_MONTH(Birthdate) = :day';
    	return Database.getQueryLocator(query);
    }
        
    global void execute(Database.BatchableContext BC, List<Contact> scope){
		//Initilize list of emails need to be sent
		list<Messaging.SingleEmailMessage> emails = new list<Messaging.SingleEmailMessage>();
        
       	//loop to every contact in scope
        for(Contact c : scope){
            //The email template Name - Use the Template Unique Name
            Messaging.SingleEmailMessage email = EmailService.getEmailTemplate('Happy_Birthday',c.Id);
            emails.add(email);
        }
        
        //If emails list not empty - send the emails
		
        if(!emails.IsEmpty())
        	Messaging.sendEmail(emails);
        
    }
        
    global void finish(Database.BatchableContext BC){
    } 
}
  • Create a schedule job; this will be used to schedule running at specific time everyday.
global class HappyBirthdaySchedule implements Schedulable {
   global void execute(SchedulableContext sc) {
        SendBirthdayEmailBatch b = new SendBirthdayEmailBatch();
        Database.executeBatch(b);
   }
}
  • Set up schedule Job to run at specific time, 7 AM for example. Setup->Apex Classes->Schedule Apex
  • The schedule runs at 7AM everyday; you will expect to see this as the result.

1 Response

  1. thank you!

Leave a comment