There are several ways to send the birthday email to the contacts in 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

  • 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
            tempID = [select Id from EmailTemplate where developername =: TempName].id;
        }catch(Exception e){
            return null; // If there is no template existed return null as error
        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 =;
        Integer 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);
        //If emails list not empty - send the 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();
  • 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.