function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Pranav ChitransPranav Chitrans 

Send Birthday Email Using batch class

Actually I want to send the Automated birthday email notification whose birthdate is excactly equal to system. today() day and month. suppose i am having one custoom object named client and under that object there is custom field named Date Of Birth and email...and what i want is I want to schedule this every day and if the d.o.b filed data in exsisting record in client object day and month is equal to system.today() day and month then send the email to that all that records whose birthdate is today and also send email to that one more client whose email i had put it by hard coding.. i had used this logic.. but failed.. I checked on apex job it shows error email is null.... i hope you all understand... what I am trying to do..plz help
global class sendGreetingWishes implements Database.Batchable<sObject>
{
 string query;
 global Database.querylocator start(Database.BatchableContext bc)
 {
  String query= 'SELECT Id, Name, email__c,birthday__c FROM stud__c';
  return Database.getQueryLocator(query);
 }

global void execute(Database.BatchableContext bc, List<stud__c> scope)
{
 for(stud__c iteratorUser : scope)
 {
   date thisdate=system.today();
   integer sysday=thisdate.day();
   integer sysmonth=thisdate.month();
   string dayandmonth=sysday+'/'+sysmonth;
   Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
   List<String> toAddresses = new List<String>();
   toAddresses.add(iteratorUser.email__c);
   email.setToAddresses(toAddresses);
   List<String> ccAddresses = new List<String>();
   ccAddresses.add('pranavlakshya009@gmail.com');
   email.setCcAddresses(ccAddresses);
   email.setSubject('Happy Birthday. Have a blast — Birthday Reminder!');
   String message = 'Happy Birthday';
   email.setHtmlBody(message);
   Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});
 }
}

 global void finish(Database.batchableContext bc)
 {
 }
}

 
Pranav ChitransPranav Chitrans
And if there is anyother other way to perform this task.. tell me that also.... 
Ketankumar PatelKetankumar Patel
Hi Pranav, 

if you are getting email is null error then you should filter out null emails from your query.
String query= 'SELECT Id, Name, email__c,birthday__c FROM stud__c where email__c != null'

 
Pranav ChitransPranav Chitrans
+Ketankumar Patel,
the process i had written above is correct???
Ketankumar PatelKetankumar Patel
Looks right to me. Do you still get any error?
Gopi MarriGopi Marri
Hello,

Use below code.It will work for your requirement.
global class SendBirthdayBatch implements Database.Batchable<sObject>,Database.Stateful 
{
    
    //global final String query = 'SELECT Id, Name, DOB__c, Email__c FROM BirthDayTracker__c WHERE DOB__c = TOMORROW ';
    global List<String> eventMessages = new List<String>();
    
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        Date tody = system.today();
        String soqlQuery = 'SELECT Id, Name, Email__c,DOB__c FROM BirthDayTracker__c WHERE DAY_IN_MONTH(DOB__c) = ' + 
            tody.day() +  ' AND CALENDAR_MONTH(DOB__c) = ' + tody.month();
        return Database.getQueryLocator(soqlQuery);
    }
    
    global void execute(Database.BatchableContext BC, List<sObject> scope)
    {
        
        List<BirthDayTracker__c> teacherList = (List<BirthDayTracker__c>) scope;
        
        List<Messaging.SingleEmailMessage> techMailList = new List<Messaging.SingleEmailMessage>();
        //Id templateId = [select id from EmailTemplate where Name = 'EmailTemplateName' LIMIT 1].id;
        
        for (BirthDayTracker__c teach : teacherList) {
            System.debug('=================teach:'+teach);
            system.debug(teach);
            
            system.debug('Send to: ' + teach.Name);
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); 
            String[] toAddresses = new String[] {teach.Email__c};
                mail.setToAddresses(toAddresses);
            mail.setSubject('Happy BirthDay ' + teach.Name);
            mail.setPlainTextBody('Happy Birthday :) ' + teach.Name);
            techMailList.add(mail);
            
        }
        if(!techMailList.isEmpty()) {
            try{
                Messaging.sendEmail(techMailList);
            }
            catch (Exception ex) {
                eventMessages.add('Unable to send email to Teacher: '+ ex.getStackTraceString());
            }
        }
    }
    
    global void finish(Database.BatchableContext BC)
    {
        AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email FROM AsyncApexJob WHERE Id = :BC.getJobId()];
        
        // Send an email to the Apex job's submitter notifying of job completion. 
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {a.CreatedBy.Email};
            mail.setToAddresses(toAddresses);
        mail.setSubject('SendBirthdayBatch: ' + a.Status);
        mail.setPlainTextBody
            ('The batch Apex job processed ' + a.TotalJobItems +' batches with '+ a.NumberOfErrors + ' failures.');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
    
}

Thanks,
Gopii.​​​​​​​

 
azhar khasimazhar khasim
Gopi errors are occurring in your code
azar khasimazar khasim
Actually I want to send the Automated birthday email notification whose birthdate is excactly equal to system. today() day and month. suppose i am having one custoom object named client and under that object there is custom field named Date Of Birth and email...and what i want is I want to schedule this every day and if the d.o.b filed data in exsisting record in client object day and month is equal to system.today() day and month then send the email to that all that records whose birthdate is today and also send email to that one more client whose email i had put it by hard coding.. i had used this logic.. but failed.. I checked on apex job it shows error email is null.... i hope you all understand... what I am trying to do..plz help

global class SampleBatchClass implements Database.Batchable<sObject>{
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        string  query ='select id,email,lastname,firstname from contact where bithday = system.today()';      
 //This is query for getting records
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext BC, List<account> AllaccountRecords){
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
         List<String> sendTo = new List<String>();
         List<String> ccTo = new List<String>();
        for(account acc : AllaccountRecords){
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    
      // Step 2: Set list of people who should get the email
     
      sendTo.add(con.Email);
      mail.setToAddresses(sendTo);
   
      mail.setSenderDisplayName(' Birthday Wishes');
    
      // (Optional) Set list of people who should be CC'ed
     
      ccTo.add('priyaaakanksha28@gmail.com');
      mail.setCcAddresses(ccTo);

      // Step 4. Set email contents - you can use variables!
      mail.setSubject(' Have a Blast Birthday ');  
            mails.add(mail);
        }
        
        if(mails.size() > 0){
            Messaging.sendEmail(mails);
        }
    }
    global void finish(Database.BatchableContext BC){
   
    }
    
}


Getting Error Like 
Variable does not exist: con.

Please help me out from this.
Very Thankful in Advance
Rajesh M 77Rajesh M 77

Hi Pranav  i follwed your code but i got this error  can you tell me how to resolve

16:04:55:032 EXCEPTION_THROWN [26]|System.EmailException: SendEmail failed. First exception on row 0; first error: SINGLE_EMAIL_LIMIT_EXCEEDED, Email limit exceeded.: []


[My Batch Class]

global class sendGreetingWishes implements Database.Batchable<sObject>
{
    global Database.querylocator start(Database.BatchableContext bc)
    {
        String query= 'SELECT Id, Name, Email,Birthdate FROM Contact where Birthdate != null';
        return Database.getQueryLocator(query); 
    }
    global void execute(Database.BatchableContext bc, List<Contact> scope)
    {
        for(Contact Usersq : scope)
        {
            date thisdate=system.today();
            integer sysday=thisdate.day();
            integer sysmonth=thisdate.month();
            string dayandmonth=sysday+'/'+sysmonth;
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            List<String> sendTo = new List<String>(); 
            sendTo.addAll((Label.Account_Mail_Notification).split(';'));
            email.setToAddresses(sendTo);
            List<String> ccAddresses = new List<String>();
            ccAddresses.add('sultanyaseen612@gmail.com');
            email.setCcAddresses(ccAddresses);
            email.setSubject('Happy Birthday. Have a blast — Birthday Reminder!');
            String message = 'Happy Birthday';
            email.setHtmlBody(message);
            Messaging.sendEmail(new Messaging.SingleEmailMessage[]{email});
        }
    }
    global void finish(Database.batchableContext bc)
    {
        //Finn
    }